我有以下内容:
import urllib
import lxml.html
connection = urllib.urlopen('http://example.com')
dom = lxml.html.fromstring(connection.read())
for link in dom.xpath('//div[@id="right-column"]//a/@href'):
print link
我的问题是,for 循环
中的每个链接
并不包含链接的整个路径,而仅包含http://example 之后的内容。 com
。
链接变量示例:
/andrew-darius-et-al-mob-app-maker
/andrew-darius-et-al-explaindio-3-0
现在,我想做的是在 for
循环中连接 connection
和 link
,这样我就有了完整路径:
http://example.com/andrew-darius-et-al-mob-app-maker
http://example.com/andrew-darius-et-al-explaindio-3-0
<小时/>
编辑1:
import urllib
import lxml.html
from urlparse import urljoin
URL = urllib.urlopen('http://muncheye.com')
dom = lxml.html.fromstring(URL.read())
for link in dom.xpath('//div[@id="right-column"]//a/@href'):
FINAL_URL = urljoin('http://muncheye.com', link)
print FINAL_URL
最佳答案
使用 urljoin
使 URL 成为绝对 URL。您必须知道,HTML 文件可以使用基本标签设置其基本 url。所以我也认为:
import urlparse
import lxml.html
URL = 'http://example.com'
dom = lxml.html.parse(URL)
url = dom.docinfo.URL
base = dom.find('head/base')
if base:
url = base.get('href', url)
for link in dom.xpath('//div[@id="right-column"]//a/@href'):
print urlparse.urljoin(url, link)
关于python - 如何在Python中将lxml字符串与另一个字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244334/