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就好了!

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