如何使用BeautifulSoup和Selenium实现if语句

时间:2019-12-14 08:33:37

标签: python beautifulsoup

并非所有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 = ""

Entire Code

1 个答案:

答案 0 :(得分:0)

使用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内获取文本