加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python:如何使用BeautifulSoup从HTML页面中提取URL?

发布时间:2020-12-16 21:57:08 所属栏目:Python 来源:网络整理
导读:我有一个包含多个div的HTML页面 我需要得到 具有类article-additional-info的所有div的值 我是BeautifulSoup的新手 所以我需要网址 "http://www.thehindu.com/news/national/gangrape-case-two-lawyers-claim-to-be-engaged-by-accused/article4332680.ece""

我有一个包含多个div的HTML页面

我需要得到< a href =>具有类article-additional-info的所有div的值
我是BeautifulSoup的新手

所以我需要网址

"http://www.thehindu.com/news/national/gangrape-case-two-lawyers-claim-to-be-engaged-by-accused/article4332680.ece"
"http://www.thehindu.com/news/cities/Delhi/power-discoms-demand-yet-another-hike-in-charges/article4331482.ece"

实现这一目标的最佳方法是什么?

最佳答案
根据您的标准,它返回三个URL(而不是两个) – 您想要过滤掉第三个吗?

基本思想是迭代HTML,只抽取你的类中的那些元素,然后迭代该类中的所有链接,拉出实际的链接:

In [1]: from bs4 import BeautifulSoup

In [2]: html = # your HTML

In [3]: soup = BeautifulSoup(html)

In [4]: for item in soup.find_all(attrs={'class': 'article-additional-info'}):
   ...:     for link in item.find_all('a'):
   ...:         print link.get('href')
   ...:         
http://www.thehindu.com/news/national/gangrape-case-two-lawyers-claim-to-be-engaged-by-accused/article4332680.ece
http://www.thehindu.com/news/cities/Delhi/power-discoms-demand-yet-another-hike-in-charges/article4331482.ece
http://www.thehindu.com/news/cities/Delhi/power-discoms-demand-yet-another-hike-in-charges/article4331482.ece#comments

这会将您的搜索范围限制为仅包含article-additional-info类标记的元素,并在其中查找所有锚点(a)标记并获取其相应的href链接.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读