1、使用 scrapy 中间件,您需要在 settings.py 中启用 HttpProxyMiddleware,例如:
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 1
}
2、爬虫代理加强版 用户名和密码认证方式,您需要在每个请求中设置 proxy 和 Proxy-Authorization 头,例如:
request = scrapy.Request(url="https://www.baidu.com/s?wd=keyword")
# 亿牛云 爬虫代理加强版 认证信息
proxyHost = "www.16yun.cn"
proxyPort = "31111"
# 代理验证信息
proxyUser = "16YUN"
proxyPass = "16IP"
# [版本>=2.6.2](https://docs.scrapy.org/en/latest/news.html?highlight=2.6.2#scrapy-2-6-2-2022-07-25)无需添加验证头,会自动在请求头中设置Proxy-Authorization
request.meta['proxy'] = "http://{0}:{1}@{2}:{3}".format(proxyUser,proxyPass,proxyHost,proxyPort)
yield request
3、采集百度关键词搜索,获取 URL,您需要在 parse 方法中解析响应内容,提取 URL,并生成新的请求或项目,例如:
def parse(self, response):
urls = response.xpath("//div[@class='result c-container ']/h3/a/@href").getall()
for url in urls:
yield scrapy.Request(url=url, callback=self.parse_url)
def parse_url(self, response):
yield {
'url': response.url
}
4、在爬虫采集的过程中,有几种方法可以将 Scrapy 输出保存为 jsonline 格式。一种方法是使用命令行选项 -O,并提供文件名和扩展名,例如:
scrapy crawl medscape_crawler -O medscape_links.jsonl
5、另一种方法是在您的 spider 或项目设置中使用 FEEDS 设置,例如:
FEEDS = {
'medscape_links.jsonl': {
'format': 'jsonlines',
'encoding': 'utf8',
'store_empty': False,
'fields': None,
'indent': 4,
'item_export_kwargs': {
'export_empty_fields': True,
},
},
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有