用pycharm软件做一个新闻搜索的代码,用URL输入要爬取的新闻网址,获取网页数据后,再抓取含有新闻关键词的标题和链接(图中关键词为python),把抓取的数据写入Excel文件中,再将其保存到桌面
完整代码如下
import requests A1A2 A
5 from bs4import BeautifulSoup
importpandasaspd
5 import os
6 #获取网页数据
2 Ur=http://www.baidu.com/
8 res = requests.getCur)
soup= BeautifulSoup(res.text, 9 whtml.parser")
19 抓取新闻标题和链接
news_titles=]
12 news_inks=
3 forinkin soup.find_al("a")
14
5 news_titles.append(link.text.
16 news_inks.append(link.get("href))
17 #将数据写入ExceL文件
18 df=pd.DataFrame(t标题:news_titles,链接:news_links})
19
26 #获取桌面路径
desktop = os.path.joinCos.path.joinCos.environl'USERPROFILE'J),Desktop')
22
23 #保存ExceL文件到桌面
df.to_excel(desktop+ 2 ninews.xLsx",index=False)
for linkin soup.find allC"a") if"python"inlink.text
运行结果如下↓
Excel文件可以保存到桌面,但是打开没有数据!!