用beautifulsoup,re,xpath爬取文章并保存为csv文件

本文展示了如何使用Python的BeautifulSoup、正则表达式(Re)和XPath库来抓取网站上的文章信息,并将数据导出到CSV文件中,适合初学者学习爬虫基础知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,直接上代码,

import csv, requests, re
from bs4 import BeautifulSoup
from lxml import etree

url = 'https://www.v2ex.com/?tab=all'
'''
#soup加正则
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
articles = []
for article in soup.find_all(class_='cell item'):
    title = article.find(class_='item_title').get_text()
    category = article.find(class_='node').get_text()
    author = re.findall(r'(?<=<a href="/member/).+(?="><img)', str(article))[0]
    #print(author)
    u = article.select('.item_title > a')
    #print(u)
    link = 'https://www.v2ex.com' + re.findall(r'(?<=href=").+(?=")', str(u))[0]
    articles.append([title, category, author, link])
print(articles)
'''

#xpath 写
response=requests.get(url).text
html=etree.HTML(response)
#print(html)

tag_div=html.xpath('//div[@class="box"]/div[@class="cell item"]')
#print(tag_div)

articles=[]
for each in tag_div:
    title=each.xpath('./table//tr/td[3]/span[1]/a/text()')[0]
    h
好的,我选择爬取新浪新闻网站的数据存储到CSV文件中。以下是实现的步骤: 1. 首先,我们需要安装必要的库来进行网页爬取解析。可以使用以下命令来安装它们: ``` pip install requests pip install beautifulsoup4 pip install pandas ``` 2. 接下来,我们需要使用requests库向新浪新闻网站发送请求,获取响应内容。以下是示例代码: ```python import requests url = 'https://news.sina.com.cn/' response = requests.get(url) if response.status_code == 200: print('请求成功!') else: print('请求失败!') ``` 3. 然后,我们需要使用beautifulsoup4库将获取的响应内容解析成HTML文档,提取出新闻标题链接。以下是示例代码: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') news_list = soup.select('.news-item') data_list = [] for news in news_list: title = news.select_one('.news-title').text.strip() link = news.select_one('.url').get('href') time = news.select_one('.time').text.strip() source = news.select_one('.source').text.strip() keywords = news.select_one('.keywords').text.strip() data_list.append([title, link, time, source, keywords]) print('爬取到的数据:') for data in data_list: print(data) ``` 4. 实现多页爬取。我们可以通过修改URL中的页码参数来爬取多页数据。以下是示例代码: ```python import requests from bs4 import BeautifulSoup data_list = [] for page in range(1, 3): # 爬取前2页数据 url = f'https://news.sina.com.cn/roll/#pageid=153&lid=2509&k=&num=50&page={page}' response = requests.get(url) if response.status_code == 200: print(f'第{page}页请求成功!') else: print(f'第{page}页请求失败!') continue soup = BeautifulSoup(response.text, 'html.parser') news_list = soup.select('.list_009 .d_list') for news in news_list: title = news.select_one('.list_009 a').text.strip() link = news.select_one('.list_009 a').get('href') time = news.select_one('.list_009 .time').text.strip() source = news.select_one('.list_009 .media_name').text.strip() keywords = news.select_one('.list_009 .keywords').text.strip() data_list.append([title, link, time, source, keywords]) print('爬取到的数据:') for data in data_list: print(data) ``` 5. 最后,我们可以使用pandas库将爬取到的数据存储到CSV文件中。以下是示例代码: ```python import pandas as pd df = pd.DataFrame(data_list, columns=['标题', '链接', '时间', '来源', '关键词']) df.to_csv('news.csv', index=False, encoding='utf-8-sig') print('数据已保存CSV文件中!') ``` 完整代码如下所示:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值