Web scraping 如何使用Scrapy自动获取请求头?
如果这个问题太愚蠢,请原谅我。 我们知道在浏览器中可以进入Inspect->Network->XHR->Header并获取请求头。然后可以将这些头添加到Scrapy请求中 但是,有没有办法使用Scrapy请求自动获取这些请求头,而不是手动获取 我尝试使用:Web scraping 如何使用Scrapy自动获取请求头?,web-scraping,scrapy,Web Scraping,Scrapy,如果这个问题太愚蠢,请原谅我。 我们知道在浏览器中可以进入Inspect->Network->XHR->Header并获取请求头。然后可以将这些头添加到Scrapy请求中 但是,有没有办法使用Scrapy请求自动获取这些请求头,而不是手动获取 我尝试使用:response.request.headers,但这些信息还不够: {b'Accept':[b'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'],b'Accep
response.request.headers
,但这些信息还不够:
{b'Accept':[b'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'],b'Accept-Language':[b'en'],b'User-Agent':[b'Mozilla/5.0(windowsnt10.0;Win64;x64)AppleWebKit/537.36(KHTML,像Gecko)Chrome/81.0.4044.129 S afari/537.36'],b'Accept-Encoding':[b'gzip,deflate'>
我们在浏览器中看到更多的请求头信息。如何获取此信息?Scrapy使用这些标题来刮取网页。有时,如果一个网站需要一些特殊的标题键(比如API),你会注意到scrapy将无法抓取网页
不过,在DownloaMiddilewares中有一个解决方法,您可以实现Selenium。因此,请求的网页将使用selenium自动浏览器下载。然后,当selenium启动实际的浏览器时,您将能够提取完整的标题
## Import webdriver from Selenium Wire instead of Selenium
from seleniumwire import webdriver
## Get the URL
driver = webdriver.Chrome("my/path/to/driver", options=options)
driver.get("https://my.test.url.com")
## Print request headers
for request in driver.requests:
print(request.url) # <--------------- Request url
print(request.headers) # <----------- Request headers
print(request.response.headers) # <-- Response headers
##从Selenium Wire而不是Selenium导入webdriver
从seleniumwire导入webdriver
##获取URL
driver=webdriver.Chrome(“my/path/to/driver”,options=options)
驱动程序。获取(“https://my.test.url.com")
##打印请求标题
对于driver.requests中的请求:
打印(request.url)#