python資料解析 bs4爬取三國演義

2021-10-19 05:36:01 字數 2337 閱讀 1273

bs4資料解析的原理:

環境安裝:

如何例項化beautifulsoup物件:

提供的用於資料解析的方法和屬性:

soup.find_all(『tagname』):返回符合要求的所有標籤(列表)

select:

獲取標籤之間的文字資料:

獲取標籤中屬性值:

需求:爬取三國演義全文

#需求:爬取三國演義**所有的章節標題和章節內容

if __name__ ==

"__main__"

:#對首頁的頁面資料進行爬取

headers =

url =

''page_text = requests.get(url=url,headers=headers)

#不寫可能會亂碼

page_text.encoding=

'utf-8'

#在首頁中解析出章節的標題和詳情頁的url

#1.例項化beautifulsoup物件,需要將頁面原始碼資料載入到該物件中

soup = beautifulsoup(page_text.text,

'lxml'

)#解析章節標題和詳情頁的url

li_list = soup.select(

'.book-mulu > ul > li'

) fp =

open

('./sanguo.txt'

,'w'

,encoding=

'utf-8'

)for li in li_list:

title = li.a.string

detail_url =

''+li.a[

'href'

]#對詳情頁發起請求,解析出章節內容

detail_page_text = requests.get(url=detail_url,headers=headers)

detail_page_text.encoding=

'utf-8'

#解析出詳情頁中相關的章節內容

detail_soup = beautifulsoup(detail_page_text.text,

'lxml'

) div_tag = detail_soup.find(

'div'

,class_=

'chapter_content'

)#解析到了章節的內容

content = div_tag.text

fp.write(title+

':'+content+

'\n'

)print

(title,

'爬取成功!!!'

亂碼這裡再舉個小例子:

亂碼了,看一下網頁的編碼方式:

可以看出****使用的是 gbk 編碼,因此,加上r.encoding = 'gbk'就可以解決了。

更多亂碼問題持續更新:python 解決中文亂碼問題

bs4爬取網頁基礎

import requests from bs4 import beautifulsoup def getsoup url try r requests.get url,timeout 30 r.raise for status print r.text 很亂 soup beautifulsoup ...

BS4爬取豆瓣電影

爬取豆瓣top250部電影 建立表 connect.py from sqlalchemy import create engine hostname localhost port 3306 username root password 123456 database douban db url my...

Python使用bs4爬取資料時亂碼問題

使用requests和beautifulsoup模組爬取網頁資料時,有時會出現亂碼情況,如下所示 需要爬去的網頁的編碼格式為 pyhton 如下所示 import requests from bs4 import beautifulsoup def get content url content d...