Python爬虫:scrapy辅助功能实用函数

举报
彭世瑜 发表于 2021/08/14 01:09:45 2021/08/14
【摘要】 scrapy辅助功能实用函数: get_response: 获得scrapy.HtmlResponse对象, 在不新建scrapy项目工程的情况下,使用scrapy的一些函数做测试 extract_links: 解析出所有符合条件的链接 代码示例 以拉勾首页为例,获取拉勾首页所有职位链接,进一步可以单独解析这些链接,获取职位的详情信息 import req...

scrapy辅助功能实用函数:

  1. get_response: 获得scrapy.HtmlResponse对象, 在不新建scrapy项目工程的情况下,使用scrapy的一些函数做测试

  2. extract_links: 解析出所有符合条件的链接

代码示例

以拉勾首页为例,获取拉勾首页所有职位链接,进一步可以单独解析这些链接,获取职位的详情信息

import requests
from scrapy.http import HtmlResponse
from scrapy.linkextractors import LinkExtractor

def get_response(url): """ 获得scrapy.HtmlResponse对象, 在不新建scrapy项目工程的情况下, 使用scrapy的一些函数做测试 :param url: {str} 链接 :return: {HtmlResponse} scrapy响应对象 """ headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0" } response = requests.get(url, headers=headers) return HtmlResponse(url=url, body=response.content)


def extract_links(response, allow, allow_domains): """ 解析所有符合要求的链接, 每次都解析不出来text属性,所以直接封装,可以做一些特定扩展 :param response: {scrapy.http.HtmlResponse} scrapy响应 :param allow: {tuple} 链接限定元组 :param allow_domains: {tuple} 域名限定元组 :return: {iterator({str})} """ link_extractor = LinkExtractor(allow=allow, allow_domains=allow_domains) links = link_extractor.extract_links(response) return (link.url for link in links)


if __name__ == '__main__': url = "https://www.lagou.com/" response = get_response(url) links = extract_links(response, ("jobs/\d+.html"), ("lagou.com",)) for link in links: print(link) """ https://www.lagou.com/jobs/5185130.html https://www.lagou.com/jobs/4200613.html https://www.lagou.com/jobs/5039140.html https://www.lagou.com/jobs/5174337.html https://www.lagou.com/jobs/5185128.html https://www.lagou.com/jobs/5185127.html ... """

  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。

原文链接:pengshiyu.blog.csdn.net/article/details/82898956

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。