我希望能够删除一系列链接。我不能直接使用BeautifulSoup,因为html的结构方式。
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中删除所有出现的内容
答案 0 :(得分:0)
start_list = soup.find_all(href=re.compile('id='))
href_list = [i['href'] for i in start_list]
href
是标记的属性,如果您使用find_all
获取大量标记,只需迭代它并使用tag['href']
来访问该属性。
要了解使用[]
的原因,您应该知道标记的属性存储在字典中。
Document:
标签可以包含任意数量的属性。标签
<b class="boldest">
有一个属性“class”,其值为“boldest”。你可以访问 通过将标记视为字典来处理标记的属性:tag['class'] # u'boldest'
您可以直接以.attrs:
的形式访问该词典tag.attrs # {u'class': u'boldest'}
list comprehension很简单,你可以引用这个PEP,在这种情况下,它可以在for循环中完成:
href_list = []
for i in start_list:
href_list.append(i['href'])