【问题标题】:How to extract URL from HTML anchor element using Python3? [closed]如何使用 Python3 从 HTML 锚元素中提取 URL? [关闭]
【发布时间】:2014-08-04 14:32:21
【问题描述】:

我想从网页 HTML 源中提取 URL。
示例:

xyz.com source code:
<a rel="nofollow" href="example/hello/get/9f676bac2bb3.zip">Download XYZ</a>

我要提取:

example/hello/get/9f676bac2bb3.zip

如何提取此网址?

我不懂正则表达式。我也不知道如何在 Windows 上安装 Beautiful Soup 4lxml。尝试安装此库时出现错误。

我试过了:

C:\Users\admin\Desktop>python
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> url = '<a rel="nofollow" href="/example/hello/get/9f676bac2bb3.zip">XYZ</a>'
>>> r = re.compile('(?<=href=").*?(?=")')
>>> r.findall(url)
['/example/hello/get/9f676bac2bb3.zip']
>>> url
'<a rel="nofollow" href="/example/hello/get/9f676bac2bb3.zip">Download XYZ</a>'
>>> r.findall(url)[0]
'/example/hello/get/9f676bac2bb3.zip'
>>> a = "https://xyz.com"
>>> print(a + r.findall(url)[0])
https://xyz.com/example/hello/get/9f676bac2bb3.zip
>>>

但这只是一个硬编码的 HTML 示例。如何获取网页源并针对它运行我的代码?

【问题讨论】:

  • 请解释一下,您在安装 BS4 或 lxml 时遇到了什么错误。

标签: python regex python-3.x python-3.2


【解决方案1】:

您可以改用内置的xml.etree.ElementTree

>>> import xml.etree.ElementTree as ET
>>> url = '<a rel="nofollow" href="/example/hello/get/9f676bac2bb3.zip">XYZ</a>'
>>> ET.fromstring(url).attrib.get('href')
'/example/hello/get/9f676bac2bb3.zip'

这适用于这个特定的示例,但xml.etree.ElementTree 不是 HTML 解析器。考虑使用BeautifulSoup

>>> from bs4 import BeautifulSoup
>>> BeautifulSoup(url).a.get('href')
'/example/hello/get/9f676bac2bb3.zip'

或者,lxml.html

>>> import lxml.html
>>> lxml.html.fromstring(url).attrib.get('href')
'/example/hello/get/9f676bac2bb3.zip'

就个人而言,我更喜欢 BeautifulSoup - 它使 html 解析变得简单、透明和有趣。


要点击链接并下载文件,您需要创建一个完整的 url,包括架构和域(urljoin() 会有所帮助),然后使用urlretrieve()。示例:

>>> BASE_URL = 'http://example.com'
>>> from urllib.parse import urljoin
>>> from urllib.request import urlretrieve
>>> href = BeautifulSoup(url).a.get('href')
>>> urlretrieve(urljoin(BASE_URL, href))

UPD(针对 cme​​ts 中发布的不同 html):

>>> from bs4 import BeautifulSoup
>>> data = '<html> <head> <body><example><example2> <a rel="nofollow" href="/example/hello/get/9f676bac2bb3.zip">XYZ</a> </example2></example></body></head></html>'
>>> href = BeautifulSoup(data).find('a', text='XYZ').get('href')
'/example/hello/get/9f676bac2bb3.zip'

【讨论】:

  • 好的。这次运行。谢谢。如何从网页中找到此代码? &lt;a rel="nofollow" &lt;href="/example/hello/get/9f676bac2bb3.zip"&gt;XYZ&lt;/a&gt; 示例:&lt;html&gt; &lt;head&gt; &lt;body&gt;&lt;example&gt;&lt;example2&gt; &lt;a rel="nofollow" &lt;href="/example/hello/get/9f676bac2bb3.zip"&gt;XYZ&lt;/a&gt; &lt;/example2&gt;&lt;/example&gt;&lt;/body&gt;&lt;/head&gt;&lt;/html&gt; UI = 用户输入 CG = 自动更改文件 ST = STATIC (get) /UI/UI/ST/CG.zip 对不起我的英语不好
猜你喜欢
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2013-03-09
  • 2013-03-08
  • 2018-11-29
  • 1970-01-01
  • 2021-05-11
  • 2014-02-12
相关资源
最近更新 更多