python爬虫一般格式
生活随笔
收集整理的這篇文章主要介紹了
python爬虫一般格式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫在前面:建議安裝BeautifulSoup模塊,寫爬蟲可以節省不少時間。一般出錯,參考終端給出的建議。
pip3 install bs4 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
伴隨bs4安裝的還有 lxml 模塊
pip3 install lxml -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
需要了解
圖片來源:https://blog.csdn.net/weixin_42170439/article/details/90445043
python正則表達式:https://www.cnblogs.com/cq146637/p/8072540.html
主要了解re.findall函數的使用。
簡單示例:
一般爬蟲的格式如下:
import re
import time
import random
import requests
from bs4 import BeautifulSoup #頁面解析模塊url="https://blog.csdn.net/"
params={'key1':'value1','key2':'value2'} #相當于https://blog.csdn.net?key1=value1&key2=value2
headers={'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}#User-Agent 使爬蟲能夠偽裝成瀏覽器訪問r=requests.get(url,headers=headers,params=params,timeout=1); #設置鏈接、請求頭、參數、超時
bsObj=BeautifulSoup(r.text,'html.parser')#轉化為bs對象
list=bsObj.findAll('div', class_='title')#查找返回頁面中標簽為div,屬性中class為title的標簽with open(r'd:\Temp\test.txt','w') as f: #將想要抓取的數據保存到文件中for i in list: #一般用到bs對象的屬性有.text,.(tag),.parentprint(i.find('h2').text.replace(' ','').replace('\n',''))#也可以是print(i.h2.text.replace(' ','').replace('\n',''))f.write(i.find('h2').text.replace(' ','').replace('\n','')+'\n')
f.close()
建議參考書籍:
《python網絡數據采集》人民郵電出版社
《python網絡爬蟲從入門到實踐》機械工業出版社
總結
以上是生活随笔為你收集整理的python爬虫一般格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言实现RSA
- 下一篇: Matlab实现图像白平衡(灰度世界法、