python爬取搜狐网的新闻

搜狐网址:http://www.sohu.com/

爬取图片中红框中的标题名和链接

 

 1 import requests
 2 from bs4 import BeautifulSoup
 3 #搜狐网
 4 newsurl = 'http://www.sohu.com/'
 5 #用get方法进行网页获取
 6 res = requests.get(newsurl)
 7 #用utf-8的编码方式
 8 res.encoding='utf-8'
 9 #获取网页的内容,并用html.parser剖析器
10 soup = BeautifulSoup(res.text,"html.parser")
11 #获取到class=news下的内容,因为他现在是一个集合所以不能直接用text,必须用for循环的形式把集合中的对象取出来这对这个对象用text
12 div = soup.select('.news')
13 content = {}
14 href = {}
15 for news in div:
16    if len(news.select('p'))>0:
17        #获取到p标签下的内容
18        p = news.select('p')
19        #把内容进行循环
20        for p1 in p:
21            #打印出内容中的文字
22            print(p1.text)
23        #获取到a标签中的内容
24        a = news.select('a')
25        #把内容进行循环
26        for a1 in a:
27            #打印出内容中href后面的内容
28            print(a1['href'])

获取网页中的标题,时间,来源和内容

爬取地址:http://www.sohu.com/a/237171122_162758?g=0?code=96866857093125675042cacc48b055b9&_f=index_cpc_1

代码如下:

 1 import requests
 2 from bs4 import BeautifulSoup
 3 newurl = "http://www.sohu.com/a/237171122_162758?g=0?code=96866857093125675042cacc48b055b9&_f=index_cpc_1"
 4 res = requests.get(newurl)
 5 res.encoding="utf-8"
 6 soup = BeautifulSoup(res.text,"html.parser")
 7 title = soup.select('.text-title')[0].select('h1')[0].text
 8 time = soup.select('.article-info')[0].select('.time')[0].text
 9 laiyuan = soup.select('.article-info')[0].select('a')[0].text
10 content = soup.select(".article")[0].select('p')
11 #print("content:"+content)
12 for content1 in content:
13     #这样出来的是带有html标签的,这样放到前台文本插件里面会保留在网页上的格式,如果想去除标签变成content1.text就好了
14     print(content1)

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值