【问题标题】:Beautiful Soup not Scraping all the visible website Data (Python 3)Beautiful Soup 不会抓取所有可见的网站数据(Python 3)
【发布时间】:2014-10-26 06:39:24
【问题描述】:

我的问题是我正在尝试抓取一堆不同的网站以查找所有可见文本以下载到 .txt 文件 - 不幸的是,我无法从这些网站获取所有可能的文本。我在下面发布了我的代码的工作示例:

import requests
from bs4 import BeautifulSoup
from collections import Counter


urls = ['https://www304.americanexpress.com/credit-card/compare']

with open('thisisanew.txt', 'w', encoding='utf-8') as outfile:
    for url in urls:
        website = requests.get(url)
        soup = BeautifulSoup(website.content)
        text = [''.join(s.findAll(text=True))for s in soup.findAll('p')]
        for item in text:
            print(item, file=outfile)

如果你测试这段代码,你得到的只是以下数据——

Ratings & Reviews for this card are currently not available
Ratings & Reviews for this card are currently not available
Ratings & Reviews for this card are currently not available
All users of our online services subject to Privacy Statement and agree to be bound by Terms of etc...

我究竟如何获得此页面上的其余可见数据?根据我的研究,我很确定这与我的 soup.findAll('p')] 参数有关,但我不知道要添加什么来获取其余数据。

【问题讨论】:

    标签: python python-3.x html-parsing beautifulsoup


    【解决方案1】:

    不要搜索段落,而是从body 获取.text

    print(soup.body.text, file=outfile)
    

    如果你想避免script标签内容被写入结果,你可以在顶层找到所有标签(见recursive=False)并加入文本:

    print(''.join([element.text for element in soup.body.find_all(lambda tag: tag != 'script', recursive=False)]))
    

    【讨论】:

    • 嗨,Alecx,我想到了,但这给了我页面上的所有数据,其中大部分是无用的(即 if(NAV==null||typeof(NAV)=="undefined") {var NAV=new Object()}NAV.RWD={body:document.getElementsByTagName) -- 这两种方法之间有折衷吗?
    • @user3682157 好吧,但是您不能轻松可靠地查看元素是否“可见”或不使用 Beautifulsoup。您至少可以跳过“脚本”标签。或者,您可以切换到 selenium,它会真正知道什么是可见的,什么是不可见的。
    • @user3682157 我已经更新了答案,包括跳过script 标签内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多