【发布时间】:2020-07-27 14:55:50
【问题描述】:
我正在尝试从<a class="hwd_sound sound audio_play_button icon-volume-up ptr" title="Pronunciation for " data-src-mp3="https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3" data-lang="en_GB"></a> 中提取下载链接。我成功了re.findall('data-src-mp3="(.*?)"', str(content1))。
我想请求一个带有BeautifulSoup 的方法,这使得我的代码需要更少的库。以下是我的完整代码:
import requests
from bs4 import BeautifulSoup
import re
url = 'https://www.collinsdictionary.com/dictionary/english-french/graduate'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
soup = BeautifulSoup(requests.get(url, headers = headers).content, 'html.parser')
for tag in soup.select('''
script,
.hcdcrt,
#ad_contentslot_1,
#ad_contentslot_2,
div.h2_entry,
div.copyright,
div.example-info,
div.share-overlay,
div.popup-overlay,
span.xr'''):
tag.extract()
content1 = ''.join(map(str, soup.select_one('.cB.cB-def.dictionary.biling').contents))
sound_url = re.findall('data-src-mp3="(.*?)"', str(content1))
print(sound_url)
和我的方法的结果
['https://www.collinsdictionary.com/sounds/hwd_sounds/EN-GB-W0037420.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0037420.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/FR-W0071410.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/fr_bachelier.mp3', 'https://www.collinsdictionary.com/sounds/hwd_sounds/63854.mp3']
非常感谢!
【问题讨论】:
-
您是否只是想获得相同的输出但不使用
re还是别的什么? -
@JackFleeting 我正在尝试使用
BeautifulSoup获得相同的输出。 -
该页面中有大约 30 个 mp3 链接 - 您想要所有这些链接还是有特定的子集?
-
检查我的答案@LAD
-
@JackFleeting 好问题,我限制在
content1。
标签: python-3.x beautifulsoup web-crawler