Skip to main content
 首页 » 编程设计

python之获取除 mailto : and tel: in BS4 Python decompose() 之外的所有 HTML 数据

2025年02月15日7haluo1

我需要从 HTML 中取出电话号码和电子邮件。

我可以得到数据。

description_source = soup.select('a[href^="mailto:"]'),   
                     soup.select('a[href^="tel:"]') 

但我不想要它。

我正在尝试使用

decompose

description_source = soup.decompose('a[href^="mailto:"]') 

我收到这个错误

TypeError: decompose() takes 1 positional argument but 2 were given

我想过用

SoupStrainer

但看起来我必须包括除 mailto 和 tel 之外的所有内容才能获得正确的信息...

这个位的完整当前代码是这个

import requests 
from bs4 import BeautifulSoup as bs4 
 
item_number = '122124438749'  
 
ebay_url = "http://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=" + item_number 
r = requests.get(ebay_url) 
html_bytes = r.text 
soup = bs4(html_bytes, 'html.parser') 
 
description_source = soup.decompose('a[href^="mailto:"]') 
#description_source. 
 
print(description_source) 

请您参考如下方法:

尝试使用 find_all()。找到该页面中的所有链接,然后检查哪些链接包含电话和电子邮件。然后使用 extract().

删除它们

使用 lxml 解析器进行更快的处理。也推荐在官方文档中使用。

import requests 
from bs4 import BeautifulSoup 
 
item_number = '122124438749'  
 
ebay_url = "http://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=" + item_number 
r = requests.get(ebay_url) 
html_bytes = r.text 
soup = BeautifulSoup(html_bytes, 'lxml') 
 
links = soup.find_all('a') 
email = '' 
phone = '' 
 
for link in links: 
    if(link.get('href').find('tel:') > -1): 
        link.extract() 
 
    elif(link.get('href').find('mailto:') > -1): 
        link.extract() 
 
print(soup.prettify()) 

您也可以使用 decompose() 代替 extract()。