簡體   English   中英

如何使用 BeautifulSoup 和 Selenium 實現 if 語句

[英]How to implement if statement with BeautifulSoup and Selenium

並非所有 eBay 列表都相同,因為某些頁面使用的格式與其他頁面不同。 我希望我的代碼找到“price”元素,如果它不存在,請嘗試不同的方法。 我創建了下面的代碼,但我想知道什么是更好的方法?

    item = driver.find_element_by_xpath('//*[@id="prcIsum"]').text.strip().split()
    if len(item.text) > 0:
        price = item.text
    item = driver.find_element_by_xpath('//*[@id="mm-saleDscPrc"]')
    if len(item.text) > 0:
        price = item.text
    else:
        price = ""

完整代碼

使用Selenium ,如果元素不存在,它將引發錯誤,因此您必須使用 try/except

import selenium.webdriver

url = 'https://toscrape.com/'
url = 'http://books.toscrape.com/'

driver = selenium.webdriver.Firefox()
driver.get(url)

try:
    item = driver.find_element_by_xpath('//tag').text.strip()
except Exception as ex:
    print(ex)
    try:
         item = driver.find_element_by_xpath('//a').text.strip()
    except Exception as ex:
         print(ex)
         item = ''

print(item)    

使用BeautifulSoup您可以獲得None (或空列表),因此您必須在收到文本之前檢查它。

import selenium.webdriver

url = 'https://toscrape.com/'
url = 'http://books.toscrape.com/'

driver = selenium.webdriver.Firefox()
driver.get(url)

from bs4 import BeautifulSoup as BS

soup = BS(driver.page_source, 'html.parser')


item = soup.find('tag')
if item:
    item = item.get_text(strip=True)
else:
    item = soup.find('a')
    if item:
        item = item.get_text(strip=True)
    else:
        item = ''

print(item)

或者你可以嘗試在ttry/except獲取文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM