【问题标题】:Saving content of a webpage using BeautifulSoup使用 BeautifulSoup 保存网页的内容
【发布时间】:2023-04-07 08:08:01
【问题描述】:

我正在尝试使用以下代码使用 BeautifulSoup 抓取网页:

import urllib.request
from bs4 import BeautifulSoup

with urllib.request.urlopen("http://en.wikipedia.org//wiki//Markov_chain.htm") as url:
    s = url.read()

soup = BeautifulSoup(s)

with open("scraped.txt", "w", encoding="utf-8") as f:
    f.write(soup.get_text())
    f.close()

问题在于它保存了Wikipedia's main page 而不是那篇特定的文章。为什么地址不起作用,我应该如何更改?

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    页面的正确网址是http://en.wikipedia.org/wiki/Markov_chain:

    >>> import urllib.request
    >>> from bs4 import BeautifulSoup
    >>> url = "http://en.wikipedia.org/wiki/Markov_chain"
    >>> soup = BeautifulSoup(urllib.request.urlopen(url))
    >>> soup.title
    <title>Markov chain - Wikipedia, the free encyclopedia</title>
    

    【讨论】:

    • 只是为了澄清:维基百科将 OP 的 URL 指向主页的原因是开头的额外斜线。前两个斜杠(在主机名之后)之间的所有内容都选择了 wiki 命名空间,并且由于命名空间 // 不存在,它只是放弃并将您重定向到首页。 (末尾的.htm 只会下载一个页面,询问您是否要创建一个名为“Markov chain.htm”的文章......)
    • @abarnert 谢谢你的注意,很好的详细解释,像往常一样。
    • 如何获取整个页面,而不仅仅是标题?
    【解决方案2】:

    @alecxe 的答案将生成:

    **GuessedAtParserWarning**: 
    No parser was explicitly specified, so I'm using the best 
    available HTML parser for this system ("html.parser"). This usually isn't a problem, 
    but if you run this code on another system, or in a different virtual environment, it 
    may use a different parser and behave differently. The code that caused this warning
    is on line 25 of the file crawl.py. 
    
    To get rid of this warning, pass the additional argument 'features="html.parser"' to
    the BeautifulSoup constructor.
    

    这是一个没有 GuessedAtParserWarning 的解决方案,使用 requests

    # crawl.py
    
    import requests
    
    url = 'https://www.sap.com/belgique/index.html'
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    
    file = path.join(path.dirname(__file__), 'downl.txt')
    
    # Either print the title/text or save it to a file
    print(soup.title)
    # download the text
    with open(file, 'w') as f:
        f.write(soup.text)
    

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2010-11-16
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 2019-10-23
      • 2012-03-02
      • 2020-02-24
      相关资源
      最近更新 更多