python爬虫——利用BeautifulSoup4爬取糗事百科的段子
生活随笔
收集整理的這篇文章主要介紹了
python爬虫——利用BeautifulSoup4爬取糗事百科的段子
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 import requests
2 from bs4 import BeautifulSoup as bs
3
4 #獲取單個(gè)頁(yè)面的源代碼網(wǎng)頁(yè)
5 def gethtml(pagenum):
6 url = 'http://www.qiushibaike.com/hot/page/'+str(pagenum)+'/?s=4949992'
7 req = requests.get(url,headers = Headers)
8 html = req.text
9 #print(html)
10 return html
11
12 #獲取單個(gè)頁(yè)面的所有段子
13 def getitems(pagenum):
14 html = gethtml(pagenum)
15 soup = bs(html,"html.parser")
16 f = soup.find_all('div','content')
17 items =[]
18 for x in f:
19 #print(x.get_text())
20 items.append(x.get_text())
21 #print(items)
22 return items
23
24 #分別打印單個(gè)頁(yè)面的所有段子
25 def getduanzi(pagenum):
26 n = 0
27 for x in getitems(pagenum):
28 n +=1
29 print('第%d條段子:\n%s' % (n,x))
30
31 #分別打印所有頁(yè)面的段子
32 def getall(bginpage,endpage):
33
34 try:
35 for pagenum in range(int(bginpage),int(endpage)+1):
36 print(('----------華麗麗的分割線【第%d頁(yè)】----------'% pagenum).center(66))
37 getduanzi(pagenum)
38 except:
39 print('頁(yè)碼輸入錯(cuò)誤,只接收正整數(shù)輸入。')
40
41 if __name__ == '__main__':
42
43 Headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
44 bginpage = input('輸入起始頁(yè):').strip()
45 endpage = input('輸入終止頁(yè):').strip()
46 getall(bginpage,endpage)
47
48
?
轉(zhuǎn)載于:https://www.cnblogs.com/gopythoner/p/6337703.html
總結(jié)
以上是生活随笔為你收集整理的python爬虫——利用BeautifulSoup4爬取糗事百科的段子的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2017.1.19切题总结
- 下一篇: Dash:程序员的好帮手(转载)