【发布时间】: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 4 或 lxml。尝试安装此库时出现错误。
我试过了:
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