[英]Scraping using Python Beautifulsoup getting the url of href that is a link
使用 Python/BeautifulSoup 來轉義一些文檔 URL 我試圖獲取一個 href 的實際鏈接。 現在 href 不是一個 HTML 鏈接,而是一個“嵌入的”鏈接,如果我在瀏覽器中將鼠標懸停在它上面,它會給我實際的 URL。
頁面的“查看源代碼”是這樣的: <li class="toctree-l2"><a class="reference internal" href="accessanalyzer.html">AccessAnalyzer</a></li>
現在下面的代碼確實可以工作並且確實為我提供了 href 字符串:
for i in soup.findAll('a', attrs={'class': 'reference internal'}):
if "AccessAnalyzer" in i:
print(i)
link = i['href']
print(link)
(output)
<a class="reference internal" href="accessanalyzer.html">AccessAnalyzer</a>
accessanalyzer.html
我想要得到的是 accessanalyzer.html 的實際 URL,它是:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/accessanalyzer.html
當我將鼠標懸停在 href 上或單擊它時,會將我帶到該 URL。
我怎樣才能得到網址? 還有具有嵌入鏈接而不是實際文本的 href 概念的名稱是什么? (所以我可以研究更多)
檢索 HREF 值后,您必須進行一些額外的處理。
您需要做的是獲取源頁面的基本 URL 路徑,並附加 HREF 值。
假設源頁面是“https://example.com/stuff/source.html”,該頁面包含一個帶有 HREF“foo.html”的鏈接。 您需要獲取源頁面的基本 URL 路徑(即“https://example.com/stuff/”並附加 HREF 值以獲取“https://example.com/stuff/foo.html” .
您可以使用dirname
函數來幫助您:
>>> dir = os.path.dirname('https://example.com/stuff/source.html')
>>> dir
'https://example.com/stuffl'
然后將兩部分連接在一起:
>>> os.path.join(dir, "foo.html")
'https://example.com/stuff/foo.html'
類似於這里描述的內容。 我相信您實際上需要某種 webdriver 自動程序(Selenium 等)來模擬懸停並獲取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.