python爬蟲--個人總結

安裝參考:https://www.jianshu.com/p/ba02079ecd2f
1.用到的知識:
Mac配置環境變量:open ~/.bash_profile
使配置環境變量生效:source ~/.bash_profile
Homebrew:用法https://brew.sh
Pip:pip並不是一種語言,而是一個Python包管理工具,主要是用於安裝 PyPI 上的 軟件包。安裝好pip之後,使用pip install 命令即可方便的安裝python lib庫。
進入爬蟲頁面:jupyter notebook
2.代碼:
from requests_html import HTMLSession
session = HTMLSession()
url = ‘https://www.jianshu.com/p/85f4624485b9’
r = session.get(url)
print(r.html.text)
r.html.links
r.html.absolute_links

sel = ‘#feedlist_id > li:nth-child(1) > div > div.title > h2 > a’
results = r.html.find(sel)
results
results[0].text

results[0].absolute_links

list(results[0].absolute_links)[0]

def get_text_link_from_sel(sel):
mylist = []
try:
results = r.html.find(sel)
for result in results:
mytext = result.text
mylink = list(result.absolute_links)[0]
mylist.append((mytext, mylink))
return mylist
except:
return None

print(get_text_link_from_sel(sel))

sel = ‘#feedlist_id > li > div > div.title > h2 > a’

print(get_text_link_from_sel(sel))

import pandas as pd
df = pd.DataFrame(get_text_link_from_sel(sel))
df.columns = [‘text’, ‘link’]
Df

df.to_csv(‘output.csv’, encoding=‘gbk’, index=False)

3.結果
在這裏插入圖片描述

在這裏插入圖片描述
3.遇到的錯誤
在from requests_html import HTMLSession時遇到
ModuleNotFoundError: No module named ‘requests’

因爲需要引入包,但我引入的是requests包,而代碼需要requests_html包
所以在終端pip3 install requests_html就好了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章