使用按xpath查找元素时出现语法错误

2024-05-23 22:50:28 发布

您现在位置:Python中文网/ 问答频道 /正文

网页抓取初学者在这里。 我正在尝试获取此网页上的项目数:https://www.asos.com/dk/maend/a-to-z-of-brands/nike/cat/?cid=4766&refine=attribute_10992:61388&nlid=mw|sko|shop+efter+brand

但是,当我使用len()-函数时,它表示语法中有错误。你知道吗

from bs4 import BeautifulSoup
import requests
import selenium
from selenium.webdriver import Firefox


driver = Firefox()

url = "https://www.asos.com/dk/maend/a-to-z-of-brands/nike/cat/?cid=4766&refine=attribute_10992:61388&nlid=mw|sko|shop+efter+brand"
driver.get(url)

items = len(driver.find_elements_by_xpath(//*[@id="product-12257648"])

for item in range(items):
    price = item.find_element_by_xpath("/html/body/main/div/div/div/div[2]/div/div[1]/section/div/article[16]/a/p/span[1]")
    print(price)

然后输出此错误:

  File "C:/Users/rasmu/PycharmProjects/du nu ffs/jsscrape.py", line 13
    items = len(driver.find_elements_by_xpath(//*[@id="product-12257648"])
                                              ^
SyntaxError: invalid syntax

Process finished with exit code 1

Tags: httpsimportdivcom网页bylenwww
1条回答
网友
1楼 · 发布于 2024-05-23 22:50:28

试试这个:

items = len(driver.find_elements_by_xpath("//*[@id='product-12257648']"))

XPath周围需要双引号。你知道吗

如果你想要所有的价格,你可以重构你的代码

from selenium import webdriver

# start driver, navigate to url
driver = webdriver.Firefox()
url = "https://www.asos.com/dk/maend/a-to-z-of-brands/nike/cat/?cid=4766&refine=attribute_10992:61388&nlid=mw|sko|shop+efter+brand"
driver.get(url)

# iterate product price elements
for item in driver.find_elements_by_xpath("//p[./span[@data-auto-id='productTilePrice']]"):

    # print price text of element
    print(item.text)

driver.close()

相关问题 更多 >