gpt4 book ai didi

python - 从 BeautifulSoup 对象获取 URL

转载 作者:行者123 更新时间:2023-12-02 03:20:59 37 4
gpt4 key购买 nike

有人正在向我的函数传递一个他使用典型调用获得的 BeautifulSoup 对象(BS4):

soup = BeautifulSoup(url)

我的代码:

def doSomethingUseful(soup):
url = soup.???

如何从 soup 对象获取原始 URL?我尝试阅读文档和 BeautifulSoup 源代码...我仍然不确定。

最佳答案

如果url变量是一个实际URL的字符串,那么你应该忘记这里的BeautifulSoup并使用相同的变量url。您应该使用 BeautifulSoup 来解析 HTML 代码,而不是简单的 URL。事实上,如果您尝试像这样使用它,您会收到警告:

>>> from bs4 import BeautifulSoup
>>> url = "https://foo"
>>> soup = BeautifulSoup(url)
C:\Python27\lib\site-packages\bs4\__init__.py:336: UserWarning: "https://foo" looks like a URL. Beautiful Soup is not an HTTP client. You should probably use an HTTP client like requests to get the document behind the URL, and feed that document to Beautiful Soup.
' that document to Beautiful Soup.' % decoded_markup

由于 URL 只是一个字符串,当您“soupify”它时,BeautifulSoup 并不真正知道如何处理它,除了将其包装在基本的 HTML 中:

>>> soup
<html><body><p>https://foo</p></body></html>

如果您仍想从中提取 URL,则可以在该对象上使用 .text,因为它是其中唯一的内容:

>>> print(soup.text)
https://foo

如果另一方面 url 根本不是真正的 URL,而是一堆 HTML 代码(在这种情况下,变量名称将非常具有误导性),那么你如何提取其中的特定链接就会引出它在你的代码中如何存在的问题。执行 find 来获取第一个 a 标记,然后提取 href 值是一种方法。

>>> actual_html = '<html><body><a href="http://moo">My link text</a></body></html>'
>>> newsoup = BeautifulSoup(actual_html)
>>> newsoup.find('a')['href']
'http://moo'

关于python - 从 BeautifulSoup 对象获取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814404/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com