Python lxml请求:只有最后一个xpath搜索正在工作



我最近尝试建立一个短卡市场(一个网站,查看卡游戏的卡价格)检查器,它通过xpath获取价格从网站上。现在我认为一切正常,直到我检查,似乎只有最后一个xpath在for循环中被添加到列表中。所有链接都被导入,当您通过xpath手工检查它们时,所有链接都可以工作。

现在我需要帮助来修复这个错误:)

我使用lxml,请求读取html并在那里找到元素

from lxml import html
import requests
price = []
name = []
links = []
xpathPrice = '/html/body/main/div[4]/section[2]/div/div[2]/div[1]/div/div[1]/div/div[2]/dl/dd[6]/text()'
xpathPrice2 = '/html/body/main/div[4]/section[2]/div/div[2]/div[1]/div/div[1]/div/div[2]/dl/dd[5]/text()'
xpathName = '/html/body/main/div[3]/div[1]/h1/text()'
with open('sample.txt', 'r') as file:
for line in file:
page = requests.get(line)
code = html.fromstring(page.content)
name.append(code.xpath(xpathName))
if code.xpath(xpathPrice) == None:
price.append(code.xpath(xpathPrice2))
else:
price.append(code.xpath(xpathPrice))


string = '----- Name ------------ Preis -----nn'
print(name)
print(price)
for i in range(0, len(name)):
string = string + str(*name[i]) + ' --> ' + str(*price[i]) + 'n'
print(string)

sample.txt的内容是一个带有如下链接的列表:

  • https://www.cardmarket.com/de/digimon/products/singles/special -释放-升压v15/ceresmon bt3 - 056 v1
  • https://www.cardmarket.com/de/WeissSchwarz/Products/Singles/GURREN-LAGANN/Later-Buddy-V-2-Triple-Rare

当你从文件中读取行,然后你得到行与n在结束-这使问题,因为它使用这个n来搜索页面-它找不到它。

可能只有文件的最后一行没有n-所以只有最后一个url给出预期的数据。

您必须使用.strip()删除n(和空格,t)

for line in file:
line = line.strip()
# ... rest...

最新更新