爬虫python自学网站_Python爬虫学习9-非登录爬取网站

以http://blog.jobbole.com/all-posts/页面为例

1、提取列表页

获取一个列表页

首页获得页面文章列表,使用css选择器进行:

article_list = response.css('#archive .floated-thumb .post-thumb a::attr(href)').extract()

Paste_Image.png

在文件中引入Request库

from scrapy.http import Request使用Request进行对上节函数的调用

def parse(self, response):

"""

1、获取文章列表页url并交给scrapy进行解析

2、获取下一个文章列表页

"""

article_list = response.css('#archive .floated-thumb .post-thumb a::attr(href)').extract()

for article in article_list:

yield Request(url=article, callback=self.parse_detail)

最后一句为对每个url调用parse_detail进行解析。这里的article的网址为带完整域名的格式,如果不是完整域名,则需要对域名进行拼接成完成域名进行解析。

首先要引入from urllib import parse,通过parse自带的parse.urljoin()进行拼接,代码为:yield Request(url=parse.urljoin(response.url, article), callback=self.parse_detail)

获取下一个列表 页

每个列表页都有“下一页”链接,通过extract_first("")来得到下一页链接,如果为空则表示完成。

next_list = response.css('.next.page-numbers::attr(href)').extract_first("")

if next_list:

yield Request(url=parse.urljoin(response.url, next_list), callback=self.parse)

2、对具体内容页面提取

解析函数如下:

def parse_detail(self, response):

title = response.css('div.entry-header h1::text').extract_first()

create_date = response.css('p.entry-meta-hide-on-mobile::text').extract()[0].replace('·','').strip()

fav_nums = response.css("span.bookmark-btn::text").extract()[0]

match_re = re.match(".*?(\d+).*", fav_nums)

if match_re:

fav_nums = match_re.group(1)

comment_nums = response.css("a[href='#article-comment'] span::text").extract()[0]

match_re = re.match(".*?(\d+).*", comment_nums)

if match_re:

comment_nums = match_re.group(1)

content = response.css(".entry").extract()[0]

tag_list = response.css('p.entry-meta-hide-on-mobile a::text').extract()

tag_list = [e for e in tag_list if not e.strip().endswith("评论")]

tags = ",".join(tag_list)

print(title, create_date, fav_nums, comment_nums, tags)

通过以上代码,即可将相应内容提取出来了。

Paste_Image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值