汽車之家資料爬取:文章連結//圖片//標題
阿新 • • 發佈:2018-12-23
(1)打印出來的東西亂碼,如何處理這個問題?
import requests response=requests.get( url='https://www.autohome.com.cn/beijing/' #最新的地址是可以出來的 # url='https://www.autohome.com.cn/news/' #老的地址會出現亂碼問題 ) print(response.text)
(2)
import requests response=requests.get( # url='https://www.autohome.com.cn/beijing/' #最新的地址是可以出來的url='https://www.autohome.com.cn/news/' #老的地址會出現亂碼問題 ) # response.encoding='utf-8' #(utf-8)這個地方又做了一下處理:依然部分亂碼 response.encoding='gbk' #(gbk)這個地方又做了一下處理:依然部分亂碼 print(response.text)
(3)
import requests response=requests.get( # url='https://www.autohome.com.cn/beijing/' #最新的地址是可以出來的url='https://www.autohome.com.cn/news/' #老的地址會出現亂碼問題 ) # response.encoding='utf-8' #(utf-8)這個地方又做了一下處理:依然部分亂碼 # response.encoding='gbk' #(gbk)這個地方又做了一下處理:依然部分亂碼 response.encoding=response.apparent_encoding #注意在這裡預設就是utf-8 #這裡和寫gbk是一樣的 print(response.text)
(4)
import requests from bs4 import BeautifulSoup response=requests.get( # url='https://www.autohome.com.cn/beijing/' #最新的地址是可以出來的 url='https://www.autohome.com.cn/news/' #老的地址會出現亂碼問題 ) response.encoding=response.apparent_encoding #注意在這裡預設就是utf-8 #這裡和寫gbk是一樣的 soup=BeautifulSoup(response.text,features='html.parser') #第一步把文字轉換成物件 #後邊的features=表示以什麼引擎,或者以什麼方式轉換 #python內建的引數是'html.parser' #這個是預設的 #python的第三方引數'features='lxml',需要額外安裝才能使用 #實際生產中都是會用lxml,效能會更好一些 target=soup.find(id='auto-channel-lazyload-article') target.find('li') #根據標籤來尋找 #繼續尋找 print(target)
(5)目前的最終版(後期有待完善) 注意註釋
import requests from bs4 import BeautifulSoup response=requests.get( # url='https://www.autohome.com.cn/beijing/' #最新的地址是可以出來的 url='https://www.autohome.com.cn/news/' #老的地址會出現亂碼問題 ) response.encoding=response.apparent_encoding #注意在這裡預設就是utf-8 #這裡和寫gbk是一樣的 soup=BeautifulSoup(response.text,features='html.parser') #第一步把文字轉換成物件 #後邊的features=表示以什麼引擎,或者以什麼方式轉換 #python內建的引數是'html.parser' #這個是預設的 #python的第三方引數'features='lxml',需要額外安裝才能使用 #實際生產中都是會用lxml,效能會更好一些 target=soup.find(id='auto-channel-lazyload-article') # obj=target.find('li') #根據標籤來尋找 #只找到一個標籤927530<li> li_list=target.find_all('li') #找所有的li標籤 #繼續尋找 #此時li_list是個列表, for i in li_list: a=i.find('a') # print(a.attrs) #有些標籤是沒有a標籤的,所以報錯 if a: print(a.attrs.get('href')) txt=a.find('h3') print(txt) #url+文字 #拿到後放到app或者資料庫中 img=a.find('img') print(img.get('src')) #圖片連結
(6)
#同學案例 #有問題 import requests from bs4 import BeautifulSoup url='https://www.autohome.com.cn/news/' response=requests.get(url) response.encoding=response.apparent_encoding # soup=BeautifulSoup(response.text,'lxml',) #沒有安裝所以報錯 soup=BeautifulSoup(response.text,'html.parser',) #沒有安裝lxml模組所以報錯 print(soup.title.text) #結果:【圖】最新汽車新聞_資訊_汽車之家