第一次使用爬虫

1.爬取新浪网
import requests
from bs4 import BeautifulSoup
res = requests.get('http://news.sina.com.cn/china/')
res.encoding = 'utf-8'

soup = BeautifulSoup(res.text,'html.parser')


for news in soup.select('.news-item'):
    if len(news.select('h2')) > 0:
        time = news.select('.time')[0].text
        h2 = news.select('h2')[0].text
        a = news.select('a')[0]['href']
        print(time,h2,a)
爬取结果:
4月8日 12:06 韩长赋任中央农村工作领导小组副组长 http://news.sina.com.cn/o/2018-04-08/doc-ifyteqtq5694371.shtml
4月8日 11:36 干部违规办宴:亲属成“白手套”朋友成“中介人” http://news.sina.com.cn/c/2018-04-08/doc-ifyuwqez6571221.shtml
4月8日 11:21 公安部副部长孟宏伟不再担任部党委委员(图) http://news.sina.com.cn/o/2018-04-08/doc-ifyuwqez6561865.shtml
4月8日 11:10 中美贸易摩擦升级 外媒:美鹰派成对华贸易战推手 http://news.sina.com.cn/c/2018-04-08/doc-ifyuwqez6553942.shtml
4月8日 11:04 刘建洋任南昌副市长 代理市长 http://news.sina.com.cn/c/2018-04-08/doc-ifyteqtq5654761.shtml
4月8日 10:59 陕西省商洛市政协原主席王甲训等2人被处分 http://news.sina.com.cn/o/2018-04-08/doc-ifyteqtq5650889.shtml
4月8日 10:50 外媒称美国对华贸易施压“没道理”:美更需要中国 http://news.sina.com.cn/c/2018-04-08/doc-ifyteqtq5643846.shtml
4月8日 10:47 WTO没有亏待美国 特朗普为何还要满腹怨气? http://news.sina.com.cn/c/2018-04-08/doc-ifyuwqez6538498.shtml

2.爬取中国知网的url
from urllib.request import urlopen#用于获取网页
from bs4 import BeautifulSoup#用于解析网页

url = urlopen('http://www.cnki.net/')
bsObj = BeautifulSoup(url, 'html.parser')
a1 = bsObj.find_all('a')
for a2 in a1:
    a3 = a2.get('href')
    print(a3)



 

猜你喜欢

转载自my.oschina.net/u/3801402/blog/1791477