【发布时间】:2020-04-24 12:07:34
【问题描述】:
我正在尝试从具有 url 列表的网页中获取 url。我不想获取所有的 url,只有文本与列表中字符串文本匹配的那些。字符串列表是网页上链接文本的子集,我通过 scraping 页面提取并删除了我不想要的文本。我有一个存储在filenames 中的字符串列表。
我正在尝试提取列表中包含字符串的链接。下面返回一个空列表
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html5lib')
links = soup.findAll('a', string = filenames[0])
file_links = [link['href'] for link in links if "export" in link['href']]
标签看起来像这样:
<p><a href="https://drive.google.com/uc?export=download&id=1wVjbdN9fztrjxhONGRX5U6N1OJDAChOi">
ECZ Mathematics Paper 2 2019.</a></p>
<p><a href="https://drive.google.com/uc?export=download&id=1x_9E3PaviCuSsqfJqOsQKOwVlCWZ1jqf">
ECZ Mathematics Paper 1 2019.</a></p>
<p><a href="https://drive.google.com/uc?export=download&id=1QFOzpPLuQPup8FtKgOoIcvzTnzCaRzUp">
ECZ Science Paper 3 2009.</a></p>
<p><a href="https://drive.google.com/uc?export=download&id=0B0lFc6TrfIg7aENYc1V6akRVVnc">
ECZ Civic Education Paper 2 2009.</a></p>
我想获得前三个而不是最后一个的 href 链接,因为字符串 'ECZ Civic Education Paper 2 2009.' 不是我的字符串列表的一部分。网站链接是here
我的字符串列表如下所示:
filenames = ['ECZ Mathematics Paper 2 2019.', 'ECZ Mathematics Paper 2 2019.',
'ECZ Science Paper 3 2009.']
我只想要前三个链接,因为链接的文本在我的列表(文件名)中。我不想要第四个链接,因为 href 链接旁边的文本(ECZ Civic Education Paper 2 2009)不在我的列表中,因为我不想下载这个文件。
【问题讨论】:
-
你能从你的stings列表中发布几个例子吗?
-
我已经编辑了帖子,包括我的列表示例
标签: python html web-scraping beautifulsoup