我正在开始web抓取并遵循教程。然而在这个代码中;nameError:名称"avail"未定义"。我想这真的很容易,但我该怎么解决呢?(错误可能出现在aval=i.text()中第15行的for循环中)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('/Users/victorfichtner/Downloads/Chromedriver')
driver.get('https://www.myntra.com/smart-watches/boat/boat-unisex-black-storm-m-
smart-watch/13471916/buy')
a = driver.find_elements_by_xpath("//*[@class='pdp-add-to-bag pdp-button pdp-flex
pdp-center']")
for i in a :
avail = i.text()
driver.quit()
print(avail)
需要注意的事项。
find_elements
返回一个list
,其中find_element
返回单个web元素- Xpath很脆
- 使用显式等待动态加载
Python
中是.text
,而不是.text()
示例代码:
driver = webdriver.Chrome('/Users/victorfichtner/Downloads/Chromedriver')
driver.maximize_window()
driver.implicitly_wait(50)
driver.get('https://www.myntra.com/smart-watches/boat/boat-unisex-black-storm-m- smart-watch/13471916/buy')
a = driver.find_elements_by_xpath("//*[contains(@class,'pdp-add-to-bag pdp-button pdp-flex')]")
avail = ""
for i in a :
avail = i.text
driver.quit()
print(avail)
输出:
ADD TO BAG