【发布时间】:2021-03-24 12:50:40
【问题描述】:
我这里有这个代码sn-p:
from bs4 import BeautifulSoup
myString = '<a href="/number-stations/german/g06" title="G06">G06</a>'
i = BeautifulSoup(str(myString), 'html.parser')
print(type(i))
print(i)
myText = i.get_text(strip=True)
print(myText)
myURL = i["href"]
print(myURL)
想法是从这个字符串中解析href。
但是,我不明白为什么它看不到它。我的输出:
<class 'bs4.BeautifulSoup'>
<a href="/number-stations/german/g06" title="G06">G06</a>
G06
Traceback (most recent call last):
File "c:\Users\user\Desktop\aaa\test.py", line 10, in <module>
myURL = i["href"]
File "C:\ProgramData\Anaconda3\lib\site-packages\bs4\element.py", line 1401, in __getitem__
return self.attrs[key]
KeyError: 'href'
BeautifulSoup 为什么看不到这个字符串的href?
【问题讨论】:
标签: python html web-scraping beautifulsoup