网页内容爬取:如何提取正文内容

创建一个新网站,一开始没有内容,通常需要抓取其他人的网页内容,一般的操作步骤如下:

根据url下载网页内容,针对每个网页的html结构特征,利用正则表达式,或者其他的方式,做文本解析,提取出想要的正文。

为每个网页写特征分析这个还是太耗费开发的时间,我的思路是这样的。

Python的BeautifulSoup包大家都知道吧,

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)

利用这个包先把html里script,style给清理了:

[script.extract() for script in soup.findAll('script')]
[style.extract() for style in soup.findAll('style')]

清理完成后,这个包有一个prettify()函数,把代码格式给搞的标准一些:

soup.prettify()

然后用正则表达式,把所有的HTML标签全部清理了:

reg1 = re.compile("<[^>]*>")
content = reg1.sub('',soup.prettify())

剩下的都是纯文本的文件了,通常是一行行的,把空白行给排除了,这样就会知道总计有多少行,每行的字符数有多少,我用excel搞了一些每行字符数的统计,如下图:

x坐标为行数,y坐标为该行的字符数

很明显,会有一个峰值,81~91行就应该是这个网页的正文部分。我只需要提取81~91行的文字就行了。

问题来了,照着这个思路,有什么好的算法能够通过数据分析的方式统计出长文本的峰值在哪几行?

附带一个开源的提取文本的python包,https://github.com/xgdlm/python-goose

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将之前提取网页内容写入CSV文件,你可以使用Python的csv模块来实现。以下是修改后的代码: ```python import os import re import csv from bs4 import BeautifulSoup # 设置html文件路径 folder_path = r'C:\Users\test\Desktop\DIDItest' output_file = r'C:\Users\test\Desktop\output.csv' # 提取html文件内所需要数据 def extract_html_info(file_path, csv_writer): with open(file_path, 'r', encoding='utf-8') as file: # 读取HTML源代码 html = file.read() soup = BeautifulSoup(html, 'html.parser') # 提取所有的<p>标签 p_tags = soup.find_all('p') for p_tag in p_tags: # 提取ID talk_id = p_tag.find_previous(string=lambda text: isinstance(text, str) and '[talkid:' in text) talk_id = talk_id.strip('[talkid:]') # 提取时间 timestamp = p_tag.find_previous('body').find_previous('head').find('meta', {'http-equiv': 'Content=-Type'})['content'] # 提取发送号码 send_number = p_tag.find('span', {'class': 'hint-success'}).text # 提取接收号码 receive_number = p_tag.find_all('span', {'class': 'hint-success'})[1].text # 提取信息内容 message = p_tag.previous_sibling.strip() # 判断是否是音频 if '音频' in message: file_url = p_tag.find('a')['href'] csv_writer.writerow([talk_id, timestamp, send_number, receive_number, file_url]) else: csv_writer.writerow([talk_id, timestamp, send_number, receive_number, message]) # 创建CSV文件并写入数据 with open(output_file, 'w', newline='', encoding='utf-8') as file: csv_writer = csv.writer(file) csv_writer.writerow(['ID', '时间', '发送号码', '接收号码', '内容']) # 遍历文件夹及子文件夹,提取HTML文件信息 for root, dirs, files in os.walk(folder_path): for file in files: if file.endswith('.html'): file_path = os.path.join(root, file) extract_html_info(file_path, csv_writer) print("数据已成功写入CSV文件。") ``` 在这个修改后的代码中,我添加了一个`output_file`变量来指定输出的CSV文件路径。然后,在`extract_html_info`函数中,我使用`csv_writer.writerow()`方法将提取的数据逐行写入CSV文件。 最后,在主程序中,我使用`open()`函数创建了CSV文件,并传递给`csv.writer()`方法创建了一个`csv_writer`对象。然后,我使用`csv_writer.writerow()`方法将表头和提取的数据写入CSV文件。 希望这次能够满足你的需求!如果你还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值