1.爬蟲的基本流程:
零基礎學python爬蟲?通過requests庫的get方法獲得網站的url
瀏覽器打開網頁源碼分析元素節點
通過BeautifulSoup或者正則表達式提取想要的數據
儲存數據到本地磁盤或者數據庫
2.正式開工啦
url = “http://www.jianshu.com”
page = requests.get(url) #發現返回狀態碼403,說明有問題出現(除200外,其他的都是有問題的)
#這個時候查看一下爬蟲的robots協議,的確有些問題,解決方案如下:
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'}獲取html頁面
page = requests.get(url, headers = headers)
demo = page.text
#記住,有時候有可能出現編碼問題
page.encoding = page.apparent_encoding
#將獲取的內容轉換為BeautifulSoup格式,并將html.parser作為解釋器(熬一鍋湯)
soup = BeautifulSoup(demo, 'html.parser')
#以格式化的形式打印html
print(soup.prettify()) #利于分析元素節點
#查找所有a標簽中class=‘tilte’的語句
titles = soup.find_all('a', 'title')
#打印查找到的每一個標簽的string和文章鏈接
for titile in titles:
print(title.string) #打印字符串
print("http://www.jianshu.com" + title.get('href')) #利用title的get方法獲取連接,可通過dir(titles)查看可用的方法
#將獲取的內容寫入本地磁盤
with open('aa.txt', 'w') as f:
for title in titles:
f.write(title.string+'\n')
f.write('http://www.jianshu.com' + title.get('href') + '\n\n')
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态