python - 从列表中抓取网站,解析全文,保存为 txt 文件 - Python
问题描述
我有一个 csv 文件中的网站列表,我想从中抓取完整的可见文本并保存为单独的 txt 文件。
我现在可以抓取网站,但它们带有完整的 HTML 代码。我有一个脚本(如下),它将取出该代码并给我可见的文本,但我在最后的步骤中遇到了麻烦。
import urllib.request
import csv
import pandas as pd
from bs4 import BeautifulSoup
from bs4.element import Comment
df = pd.read_csv('~/ids.csv', sep = ',')
df.head()
def tag_visible(element):
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def text_from_html(body):
soup = BeautifulSoup(body, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.strip() for t in visible_texts)
for i in df.message_id:
fp = urllib.request.urlretrieve('url='+str(i))
l = text_from_html(fp) #<<<---ERROR HERE
file = open(str(i)+".txt","w",encoding='utf-8')
file.close()
file.write(l)
我得到一个TypeError: expected string or bytes-like object
. 对于可能是一个基本问题的道歉。
解决方案
你缺少一个括号。
fp = urllib.request.urlretrieve('url='+str(i))
^
推荐阅读
- c++ - 索引和替换的计算成本
- c# - 不同大小的游戏对象之间的 2d 跑步者相同的间距
- spring-boot - 在 spring-boot-starter-web 项目中实现 HATEOAS 的最佳方法是什么?
- reactjs - React Router V4 - 如何只有参数?
- html - 在移动设备或小显示器上切换悬停效果以链接
- java - 有没有办法在 jhipster 中有一个单独的微服务用于登录?
- vba - 在连接的字符串变量上使用 find 时出现 vba 错误
- r - 根据条件和列名字符串更改多个列
- javascript - Promise.all 具有不同的返回类型
- codeigniter - 如何在codeigniter中打开一个对话框?