使用BeautifulSoup进行网页抓取将不起作用

2024-10-01 17:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

最终,我会尝试打开一个新闻网站的所有文章,然后在所有文章中使用的单词前10名。为了做到这一点,我首先想看看有多少篇文章,这样我就可以在某个时候对它们进行迭代,但我还没有真正弄清楚我想如何做每件事

为此,我想使用BeautifulSoup4。我想我想得到的类是Javascript,因为我没有得到任何回报。 这是我的代码:

url = "http://ad.nl"
ad = requests.get(url)
soup = BeautifulSoup(ad.text.lower(), "xml")
titels = soup.findAll("article")

print(titels)
for titel in titels:
    print(titel)

物品名称有时是h2或h3。它总是有一个和同一个类,但我不能通过该类得到任何东西。它有一些父级,但它使用相同的名称,但以扩展包装器为例。我甚至不知道如何使用父类来获得我想要的,但我认为这些类也是Javascript。还有一个我感兴趣的href。但再一次,这可能也是Javascript,因为它不返回任何内容

有人知道我如何使用BeautifulSoup使用任何东西(最好是href,但文章名称也可以)吗


Tags: 名称url网站文章javascript单词新闻ad
2条回答

正如@Sri在评论中提到的,当你打开该url时,你会看到一个页面,你必须首先接受cookies,这需要交互。 当你需要交互时,考虑使用一些类似于硒的东西(https://selenium-python.readthedocs.io/)。

这里有一些东西应该让你开始

(编辑:在运行下面的代码之前,您需要运行pip install selenium

import requests
from bs4 import BeautifulSoup
from selenium import webdriver

url = 'https://ad.nl'

# launch firefox with your url above
# note that you could change this to some other webdriver (e.g. Chrome)
driver = webdriver.Firefox()
driver.get(url)

# click the "accept cookies" button
btn = driver.find_element_by_name('action')
btn.click()

# grab the html. It'll wait here until the page is finished loading
html = driver.page_source

# parse the html soup
soup = BeautifulSoup(html.lower(), "html.parser")
articles = soup.findAll("article")

for article in articles:
    # check for article titles in both h2 and h3 elems
    h2_titles = article.findAll('h2', {'class': 'ankeiler__title'})
    h3_titles = article.findAll('h3', {'class': 'ankeiler__title'})
    for t in h2_titles:
        # first I was doing print(t.text), but some of them had leading
        # newlines and things like '22:30', which I assume was the hour of the day
        text = ''.join(t.findAll(text=True, recursive=False)).lstrip()
        print(text)
    for t in h3_titles:
        text = ''.join(t.findAll(text=True, recursive=False)).lstrip()
        print(text)

# close the browser
driver.close()

这可能不是你想要的,但这只是一个如何使用硒和靓汤的例子。请随意复制/使用/修改您认为合适的内容。 如果您想知道使用什么选择器,请阅读@JL Peyret的评论

以防你不想使用硒。这对我有用。我在两台不同互联网连接的电脑上试过。你能试试吗

from bs4 import BeautifulSoup
import requests

cookies={"pwv":"2",
"pws":"functional|analytics|content_recommendation|targeted_advertising|social_media"}

page=requests.get("https://www.ad.nl/",cookies=cookies)

soup = BeautifulSoup(page.content, 'html.parser')

articles = soup.findAll("article")

然后按照kimbo的代码提取h2/h3

相关问题 更多 >

    热门问题