我试着在网上搜索很多网站,但其中之一是Shopify (AFAIK)支持的“莱姆犯罪”。我使用的是lxml库,但是当我尝试使用xpath转到一个元素时,我得到了一个空数组,但它实际上存在于网页中。
import requests
from lxml import html
url = "https://limecrime.com/collections/unicorn-hair-full-coverage"
response = requests.get(url)
byte_data = response.content
source_code = html.fromstring(byte_data)我尝试过source_code.cssselect("a.CF-Product__ImageWrapper")或source_code.cssselect("CF-Product__ImageWrapper"),但都不起作用。有没有人能帮我弄到所有产品的链接?
发布于 2020-07-28 08:19:24
这可能很简单,因为你正在寻找的内容是在第二阶段用一些Javascript加载的,但是不是在html页面中你指定的url。
使用response无法做到这一点:数据不在那里。作为另一种选择,您可以查看headless chrome automation。出现在脑海中的库是puppeteer和Python版本pyppeteer。
无头浏览器库允许您实质上运行一个完整浏览器的实例,它将解析和下载每个资源,就像您在屏幕上看到的一样,并在最后为您提供一个完整的DOM进行解析。
发布于 2020-07-28 08:26:29
不,它不会。你可能正在尝试解析一个在Javascript中生成的元素,或者至少在Javascript中分配了它的类。
lxml不会运行Javascript代码,它只会解析你从那个网址下载的原始超文本标记语言。您可以通过终端查看HTML:
curl -s "https://limecrime.com/collections/unicorn-hair-full-coverage" | grep "CF-Product__ImageWrapper"您可以看到它返回零行。
如果您想查看实际的响应,您可以只使用:
curl -s "https://limecrime.com/collections/unicorn-hair-full-coverage"
这将准确地显示您的代码正在解析的内容。
发布于 2020-07-28 08:26:43
要获取页面的源代码,可以使用requests和BeautifulSoup
import requests
from lxml import html
from bs4 import BeautifulSoup
url = "https://limecrime.com/collections/unicorn-hair-full-coverage"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0)
Gecko/20100101 Firefox/78.0'}
s = requests.session()
s.headers.update(headers)
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
print (soup)https://stackoverflow.com/questions/63125246
复制相似问题