【问题标题】:Removing unwanted html from an href tag in Python [duplicate]从 Python 中的 href 标记中删除不需要的 html [重复]
【发布时间】:2017-05-16 04:57:36
【问题描述】:

我希望能够刮出链接列表。由于 html 的结构方式,我不能直接使用 BeautifulSoup。

start_list = soup.find_all(href=re.compile('id='))

print(start_list)

[<a href="/movies/?id=actofvalor.htm"><b>Act of Valor</b></a>,
 <a href="/movies/?id=actionjackson.htm"><b>Action Jackson</b></a>]

我只想提取 href 信息。我正在考虑某种过滤器,我可以将所有粗体标签放入一个列表中,然后将它们从另一个包含上述信息的列表中过滤出来。

start_list = soup.find_all('a', href=re.compile('id='))

start_list_soup = BeautifulSoup(str(start_list), 'html.parser')

things_to_remove = start_list_soup.find_all('b')

这个想法是能够遍历 things_to_remove 并从 start_list 中删除所有出现的内容

【问题讨论】:

  • 发布你想要的输出。

标签: python-3.x web-scraping beautifulsoup filtering


【解决方案1】:
start_list = soup.find_all(href=re.compile('id='))

href_list = [i['href'] for i in start_list]

href是标签的属性,如果你使用find_all获取一堆标签,只需遍历它并使用tag['href']访问属性。

要了解为什么使用[],您应该知道标签的属性存储在字典中。 Document:

一个标签可以有任意数量的属性。标签&lt;b class="boldest"&gt; 有一个属性“class”,其值为“boldest”。您可以访问一个 通过将标签视为字典来处理标签的属性:

tag['class']
# u'boldest'

您可以直接以 .attrs 访问该字典:

tag.attrs
# {u'class': u'boldest'}

列表推导很简单,可以参考这个PEP,在这种情况下,可以在for循环中完成:

href_list = []
for i in start_list:
    href_list.append(i['href'])

【讨论】:

  • 这正是我所需要的,你能向我解释一下列表理解吗?
  • 具体来说:这部分 i['href'] 为什么要放在括号里?
  • @Chace Mcguyer 请接受此答案以结束此问题。
猜你喜欢
  • 2012-03-28
  • 2023-04-02
  • 1970-01-01
  • 2013-10-24
  • 2017-01-05
  • 2019-06-02
  • 2020-09-27
  • 2019-03-30
  • 1970-01-01
相关资源
最近更新 更多