Python 使用BeautifulSoup在源代码中获取完整URL
所以我在看一些源代码,我发现了一些代码Python 使用BeautifulSoup在源代码中获取完整URL,python,Python,所以我在看一些源代码,我发现了一些代码 <img src="/gallery/2012-winners-finalists/HM_Watching%20birds2_Shane%20Conklin_MA_2012.jpg" 现在,在源代码中,链接是蓝色的,当您单击它时,它会将您带到图片所在的完整URL,我知道如何使用Beautiful Soup获得Python源代码中显示的内容,我想知道如何在单击源代码中的链接后获得完整URL 编辑: 如果给我函数为您执行此操作: >>从urllib.
<img src="/gallery/2012-winners-finalists/HM_Watching%20birds2_Shane%20Conklin_MA_2012.jpg"
现在,在源代码中,链接是蓝色的,当您单击它时,它会将您带到图片所在的完整URL,我知道如何使用Beautiful Soup获得Python源代码中显示的内容,我想知道如何在单击源代码中的链接后获得完整URL
编辑:
如果给我函数为您执行此操作:
>>从urllib.parse导入urljoin
>>>基地组织http://example.com/foo/bar.html'
>>>href='/folder/big/a.jpg'
>>>urljoin(基本,href)
'http://example.com/folder/big/a.jpg'
对于Python 2,函数在模块中。您可以发布html吗?(要加入主机和相对/绝对URL,请参阅:)@user2476540那么a
标记中指定的URL是错误的。我上面解释的是浏览器在看到带有前导斜杠的相对URL时的行为。
from bs4 import BeautifulSoup
import requests
import lxml
r = requests.get("http://example.com")
url = r.url # this is base url
data = r.content # this is content of page
soup = BeautifulSoup(data, 'lxml')
temp_url = soup.find('a')['href'] # you need to modify this selector
if temp_url[0:7] == "http://" or temp_url[0:8] == "https://" : # if url have http://
url = temp_url
else:
url = url + temp_url
print url # this is your full url