首页 > 解决方案 > 从列表中抓取网站,解析全文,保存为 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. 对于可能是一个基本问题的道歉。

标签: pythonbeautifulsoup

解决方案


你缺少一个括号。

fp = urllib.request.urlretrieve('url='+str(i))
                                             ^

推荐阅读