【问题标题】:Cannot Parse 'href' From String In BeautifulSoup4无法从 BeautifulSoup4 中的字符串解析“href”
【发布时间】: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


    【解决方案1】:

    当您尝试使用i["href"] 访问href 时,您的访问方式就像是dict,但事实并非如此。您必须首先使用.find() 方法找到标签。

    from bs4 import BeautifulSoup
    
    myString = '<a href="/number-stations/german/g06" title="G06">G06</a>'
    
    soup = BeautifulSoup(myString, 'html.parser')
    
    print(soup.find('a').attrs)
    print('-' * 10)
    print(soup.find('a')['href'])
    

    输出:

    {'href': '/number-stations/german/g06', 'title': 'G06'}
    ----------
    /number-stations/german/g06
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2018-09-21
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多