python url 正则表达式

0 投票
2 回答
672 浏览
提问于 2025-04-16 02:25

我有一个正则表达式(regexp),我想把它的输出加到我的网址里。

比如说:

url = 'blabla.com'
r = re.findall(r'<p>(.*?</a>))

r output - /any_string/on/any/server/

但是我不知道怎么用正则表达式的输出去做一个获取请求(get-request)。

blabla.com/any_string/on/any/server/

2 个回答

0

只需要获取 Beautiful Soup:

http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing+a+Document

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
soup.findAll('p')
2

不要用正则表达式来解析HTML,应该用真正的解析器。

我建议使用lxml.html解析器。lxml支持xpath,这是一种非常强大的查询结构化文档的方法。它还有一个现成的make_links_absolute()方法,可以直接满足你的需求。而且速度也很快。

举个例子,在这个问题页面的HTML源代码中(就是你现在正在阅读的这个页面),有这么一部分:

<li><a id="nav-tags" href="/tags">Tags</a></li>

这个xpath表达式//a[@id='nav-tags']/@href的意思是:"获取所有<a>标签中,id属性等于nav-tagshref属性"。我们来用一下:

from lxml import html

url = 'http://stackoverflow.com/questions/3423822/python-url-regexp'

doc = html.parse(url).getroot()
doc.make_links_absolute()
links = doc.xpath("//a[@id='nav-tags']/@href")
print links

结果是:

['http://stackoverflow.com/tags']

撰写回答