我正在尝试从网站上抓取一些营养数据,到目前为止一切似乎都进展顺利,直到我遇到格式略有不同的页面。
使用 selenium 和这样的行,返回一个空列表:
values = browser.find_elements_by_class_name('size-12-fl-oz' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value')
Run Code Online (Sandbox Code Playgroud)
print 会返回这个:
[]
[]
[]
[]
[]
Run Code Online (Sandbox Code Playgroud)
但如果我定义了元素位置,那么它就可以正常工作:
kcal = data.find_elements_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=1]").text
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,当我迭代时,页面与页面之间的元素不相同。因此,如果位置 9 不存在 div,则会抛出错误。
现在,当我返回并尝试编辑代码来执行 a 时try/catch
,我得到:
AttributeError:“列表”对象没有属性“find_element_by_xpath”
或者
AttributeError:“列表”对象没有属性“find_elements_by_xpath”
这是代码,其中有我在来回测试中注释掉的区域。
import requests, bs4, urllib2, csv
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Firefox()
...
#Loop …
Run Code Online (Sandbox Code Playgroud)