Toda mi ambición es ser libre toda mi vida.
2019python爬虫入门爬取腾讯新闻[world板块][BeautifulSoup库利用]
2019python爬虫入门爬取腾讯新闻[world板块][BeautifulSoup库利用]

2019python爬虫入门爬取腾讯新闻[world板块][BeautifulSoup库利用]

2019python爬虫爬取腾讯新闻[world板块][BeautifulSoup库利用

  • 作为一个python小白,这是第一次发博客啦,现在入坑web开始学习python爬虫
  • 今天发布的是一个爬取腾讯新闻world的爬虫编写。
  • 废话不多说,直接上爬取过程吧
  • [ ] 先登陆这个界面https://new.qq.com/ch/world/看一看:在这里插入图片描述
  • [ ] 我们将要爬取的就是这以下的新闻内容
  • [ ] 先写上代码头吧
import requests
from bs4 import BeautifulSoup
import csv
  • [ ] 首先我们先爬取一下每一篇文章的链接
  • [ ] 先打开web开发者看一下:在这里插入图片描述
  • [ ] 可以发现每篇文章的url都是在div标签class属性值为”detail”下面的,先select(“.detail”)可以把所有的文章此处都选择,然后分别判断h3标签,选择a标签,得出的是字典,选出第一个的[0],其键’href’的值则是我们要选择的链接。贴代码:
urls = []
for new in soup.select(".detail"):
    if len(new.select('h3'))>0:
        href = new.select('a')[0]['href']
        urls.append(href)

这样就可以把每篇文章的链接放入urls[]数组中

  • [ ] 在有了每篇文章的链接我们就上爬取每篇文章标题和内容的代码吧,我们先点击第一篇文章的链接,用web开发者工具选择文章标题:在这里插入图片描述可以发现我们的标题在h1标签内,所以可以直接选择h1标签下的文字,贴代码:
soup.select('h1')[0].string
  • [ ] 剩下的就是爬取内文了,以本篇文章为例,web开发器选择:在这里插入图片描述发现文字都保存在p标签class属性值为”content-article”下的,贴代码:
p.text.strip() for p in soup.select('.content-article p')

p是我们设置的局部变量,此代码为选择content-article下面所有的p标签,并返回p标签内的文本(strip()去掉文本两边括号)

  • [ ] 我们的代码差不多完成了,现在就看一下总代码吧:
import requests
from bs4 import BeautifulSoup
import csv

def getNEWS(url):
    news = {}
    r = requests.get(url)
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text, 'html.parser')
    news['link:'] = url
    news['title:'] = soup.select('h1')[0].string
    news['content:'] = ','.join(p.text.strip() for p in soup.select('.content-article p'))
    #with open('data.csv','a',encoding='utf-8') as csvfile:
        #fieldnames = ['link','title','content']
        #writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        #writer.writerow({'link':news['link:'],'title':news['title:'],'content':news['content:']})
    print(news)
    print('\n')

url = 'https://new.qq.com/ch/world/'
r = requests.get(url)
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'html.parser')

#爬取链接
urls = []
for new in soup.select(".detail"):
    if len(new.select('h3'))>0:
        href = new.select('a')[0]['href']
        urls.append(href)

for url in urls:
    getNEWS(url)
  • [ ] 得到的结果大致如下(太多了一下子放不出来):在这里插入图片描述
  • [ ] 中间的注释掉的是将结果保存进.csv后缀的文件,去掉注释,并把打印注释掉:
with open('data.csv','a',encoding='utf-8') as csvfile:
        fieldnames = ['link','title','content']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'link':news['link:'],'title':news['title:'],'content':news['content:']})

    #print(news)
    #print('\n')

可以得到结果大概如下:在这里插入图片描述

  • [ ] 差不多就这样啦!有问题的话请告诉博主,我会改的,大家一起进步呀!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注