Python BeautifulSoup 提取特定的 URL

标签 python python-2.7 web-scraping beautifulsoup

是否可以只获取特定的 URL?

喜欢:

<a href="http://www.iwashere.com/washere.html">next</a>
<span class="class">...</span>
<a href="http://www.heelo.com/hello.html">next</a>
<span class="class">...</span>
<a href="http://www.iwashere.com/wasnot.html">next</a>
<span class="class">...</span>

输出应该只是来自 http://www.iwashere.com/

的 URL

例如,输出 URL:

http://www.iwashere.com/washere.html
http://www.iwashere.com/wasnot.html

我是用字符串逻辑做的。 BeautifulSoup有什么直接的方法吗?

最佳答案

您可以匹配多个方面,包括对属性值使用正则表达式:

import re
soup.find_all('a', href=re.compile('http://www\.iwashere\.com/'))

哪个匹配(对于你的例子):

[<a href="http://www.iwashere.com/washere.html">next</a>, <a href="http://www.iwashere.com/wasnot.html">next</a>]

所以任何<a>带有 href 的标签具有以字符串 http://www.iwashere.com/ 开头的值的属性.

您可以遍历结果并只挑选出 href属性:

>>> for elem in soup.find_all('a', href=re.compile('http://www\.iwashere\.com/')):
...     print elem['href']
... 
http://www.iwashere.com/washere.html
http://www.iwashere.com/wasnot.html

要改为匹配所有相对路径,请使用否定前瞻断言来测试该值是否以架构(例如 http:mailto: )或双斜杠开头( //hostname/path );任何这样的值必须改为相对路径:

soup.find_all('a', href=re.compile(r'^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))

关于Python BeautifulSoup 提取特定的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15313250/

相关文章:

python - Sphinx 自动摘要生成表中的自动换行

python - 如何在特定字符(实际上是一组字符)处拆分字符串,但具有指定的长度

python - 应用transform() pandas时如何识别变化的值

python-3.x - 如何让 pylint 在 VS Code 中使用 python 3?

linux - python : using function

python - "AttributeError: ' str ' object has no attribute ' 后代使用 bs4 和 selenium 进行自动抓取时出现错误

python - 将数组拆分为均匀分布的 block

python - 从 os.path.isfile() 函数接收 AttributeError

javascript - Request.js 无法与 Browserify 正常工作

python - 无法从 BeautifulSoup4 中的字符串解析 'href'