[英]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.