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.结果
python爬虫--个人总结_第1张图片

python爬虫--个人总结_第2张图片
3.遇到的错误
在from requests_html import HTMLSession时遇到
ModuleNotFoundError: No module named ‘requests’

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

你可能感兴趣的:(python)