【问题标题】:How to remove AttributeError for missing xpath text?如何删除缺少 xpath 文本的 AttributeError?
【发布时间】:2021-03-26 17:31:54
【问题描述】:

我试图从这两个网址返回三件事:标题、价格和详细信息。在第一个链接上,没有销售或促销,所以 xpath 是

//*[@id="priceblock_ourprice"]

第二个有销售,xpath 是

//*[@id="priceblock_dealprice"]

我只希望此脚本返回具有 ourprice xpath 而不是 dealprice xpath 的 url 的值。如果 ourprice xpath 不存在,我希望返回“N/A”。我在这里错过了什么?

from requests_html import HTMLSession
import pandas as pd

urls = ['http://amazon.com/dp/B01KZ6V00W',
'http://amazon.com/dp/B089FBPFHS'
          ]

def getPrice(url):
    s = HTMLSession()
    r = s.get(url)
    r.html.render(sleep=1,timeout=20)
    product = {
        'title': str(r.html.xpath('//*[@id="productTitle"]', first=True).text),
        'price': str(r.html.xpath('//*[@id="priceblock_ourprice"]', first=True).text),
        'details': str(r.html.xpath('//*[@id="detailBulletsWrapper_feature_div"]', first=True).text)
    }
    res = {}
    for key in list(product):
        res[key] = product[key].replace('\n',' ')

    print(res)
    return res

prices = []
for url in urls:
    prices.append(getPrice(url))


df = pd.DataFrame(prices)
print(df.head(15))
df.to_csv("testfile.csv",index=False)
print(len(prices))

回溯第二个 url,第一个 url 成功完成

line 14, in getPrice
    'price': str(r.html.xpath('//*[@id="priceblock_ourprice"]', first=True).text),
AttributeError: 'NoneType' object has no attribute 'text'

【问题讨论】:

  • 通过调用.text,您将触发AttributeError。我建议将您的 xpath 调用分配给一个变量,然后将其分配给您的价格键,例如 {"price": xpath_var if xpath_var else "N/A"}
  • @gallen 我应该把这份声明放在哪里?
  • 变量将在product 字典的定义之前定义。然后,您将使用我建议的 sn-p 更新 price 键的值的定义。

标签: python pandas xpath web-scraping python-requests


【解决方案1】:

试试这个代码:

title = r.html.xpath('//*[@id="productTitle"]', first=True)
price = r.html.xpath('//*[@id="priceblock_ourprice"]', first=True)
details = r.html.xpath('//*[@id="detailBulletsWrapper_feature_div"]', first=True)

product = {
        'title': str(title.text) if title else 'N/A',
        'price': str(price.text) if price else 'N/A',
        'details': str(details.text) if details else 'N/A'
    }

附:我认为文本已经以字符串格式返回,因此您不需要使用str(title.text),而只需使用title.text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多