![](/img/trans.png)
[英]Python : AttributeError: 'list' object has no attribute 'is_absolute'
[英]AttributeError: 'list' object has no attribute 'absolute_links'
from requests_html import HTMLSession
url = 'https://www.walmart.com/search?q=70+inch+tv&page=2&affinityOverride=default'
s = HTMLSession()
r = s.get(url)
r.html.render(sleep=1,timeout=20)
product = r.html.find('div.mb1.ph1.pa0-xl.bb.b--near-white.w-25')
productinfo = []
for item in product.absolute_links:
# ra = s.get(item)
# name = ra.html.find('h1',first=True).text
products = {
'link' :item,
}
productinfo.append(products)
print(productinfo)
print(len(productinfo))
Output
for item in product.absolute_links:
AttributeError: 'list' object has no attribute 'absolute_links'
我想獲取每個產品的鏈接,而不是通過 requests-html 庫從該網站抓取一些數據,但我收到屬性錯誤。請幫助我。檢查網站 html
但是我可以通過 requests-html 庫解決驗證碼和日志記錄問題嗎? 我對 requests-html 庫不是很熟悉
我也不是,但您可以將瀏覽器中的請求粘貼到https://curlconverter.com/ (他們也有關於如何復制請求的說明),他們會將其轉換為 python 代碼,用於帶有標頭和 cookies 的請求然后您可以將其粘貼到您的代碼中。 他們代碼的最后一行將是response = requests.get(.....
,但您可以將其替換為r = s.get(...
這樣您的代碼仍然可以使用requests_html
方法,例如.html.render
和.absolute_links
( requests
不解析 HTML)。
請記住, cookies 可能會在幾個小時內過期,如果您想繼續以這種方式抓取,您必須在那時再次從瀏覽器復制它們。
for item in product.absolute_links: AttributeError: 'list' object has no attribute 'absolute_links'
您只能將.absolute_links
應用於一個元素,而.find
返回一個元素列表(除非您指定first=True
)。 此外.absolute_links
返回一組鏈接 [即使該組僅包含一個鏈接],因此您需要循環遍歷它們或轉換為列表並通過索引訪問它以獲取鏈接。
product = r.html.find('div.mb1.ph1.pa0-xl.bb.b--near-white.w-25')
productinfo = []
for prod in product:
item = prod.absolute_links # get product link/s
# ra = s.get(list(item)[0]) # go to first product link
# name = ra.html.find('h1',first=True).text
products = {'link' :item, }
productinfo.append(products)
或者,為了絕對確保您循環訪問唯一的網址,
product = r.html.find('div.mb1.ph1.pa0-xl.bb.b--near-white.w-25')
prodUrls = set().union(*[d.absolute_links for d in product]) # combine all sets of product links
productinfo = []
for item in prodUrls:
# ra = s.get(item)
# name = ra.html.find('h1',first=True).text
products = {'link' :item, }
productinfo.append(products)
順便說一句,如果它沒有找到任何產品,那么即使錯誤消失了,你也不會得到任何鏈接,所以添加一行來打印請求狀態(以防出現問題)以及有多少產品並提取了鏈接。
print(r.status_code, r.reason, f' - {len(product)} products and {len(prodUrls)} product links from', r.url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.