[英]how to solve double 403 response in web scraping with scrapy
我試圖從這個網站上獲取文章。 我試過的:
但是當我嘗試首先運行我的代碼時得到響應 403,然后我嘗試通過在請求start_urls
時添加標題來修復它,就像我從一些答案中讀取的內容一樣。 我做到了,但后來我的腳本給了我錯誤,當進入我需要的所有信息都在那里的子 URL 時,它說響應 403。
我當前的代碼如下
import scrapy
from scrapy import Request
from scrapy.crawler import CrawlerProcess
class climateupdate(scrapy.Spider):
name = 'climateupdate'
start_urls = ['http://www.bom.gov.au/climate/updates/']
def start_requests(self):
headers= {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
for url in self.start_urls:
yield Request(url, headers=headers)
def parse(self, response):
for link in response.xpath('//*[@id="content"]/ul/li[1]/a/@href'):
yield response.follow(
url=link.get(),
callback=self.parse_item
)
def parse_item(self, response):
yield {
'date': response.xpath('//*[@id="updates"]/p[1]/time/text()').extract(),
'title': response.xpath('//*[@id="updates"]/div[1]/h1/text()').get(),
'text':''.join([x.get().strip() for x in response.xpath('//*[@class="key-points box-notice bg-grey"]//p//text()')])
}
if __name__ == '__main__':
process = CrawlerProcess()
process.crawl(weeklymining)
process.start()
我應該如何編寫腳本才能進入子 url 並獲取有關文章的所有詳細信息。
先感謝您。
在這里使用標題是不正確的,這就是你得到403
的原因
使用自定義設置注入用戶代理
您選擇 xpath 表達式的date and text
不正確
//*[@id="content"]/ul/li[1]/a/@href
只選擇一個細節url
完整的工作代碼:
import scrapy
from scrapy import Request
from scrapy.crawler import CrawlerProcess
class climateupdate(scrapy.Spider):
name = 'climateupdate'
start_urls = ['http://www.bom.gov.au/climate/updates/']
custom_settings = {
'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
'DOWNLOAD_DELAY': 1,
'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
def start_requests(self):
for url in self.start_urls:
yield Request(url,callback=self.parse)
def parse(self, response):
for link in response.xpath('//*[@class="list-archive"]/li/a/@href'):
yield response.follow(
url=link.get(),
callback=self.parse_item
)
def parse_item(self, response):
yield {
'date': response.xpath('//*[@id="updates"]/p[1]/time/text()').get(),
'title': ''.join(response.xpath('//*[@id="updates"]//h1//text()').getall()).strip(),
'text':''.join(response.xpath('//*[@id="updates"]//p//text()').getall()[1:]).strip()
}
if __name__ == '__main__':
process = CrawlerProcess()
process.crawl(weeklymining)
process.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.