python - 如何在Python中将lxml字符串与另一个字符串连接

标签 python

我有以下内容:

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 循环中连接 connectionlink ,这样我就有了完整路径:

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/

相关文章:

python - "Unexpected EOF"连接到 SQL Server

python - Django Elastic Beanstalk 部署显示 404

python - 按列值过滤 Pandas 分类数据框,然后更新其类别

使用 Beaglebone Black Angstrom 通过半双工 RS-485 分线板实现自动 RTS 的 Python PySerial

python - cv2 轮廓无法检测到某些形状

python - 字典的区别

python - 在 Pandas 中使用多索引标题读取 excel 时选择列

python - pytest capsys : checking output AND getting it reported?

python - 来自具有相同父级但不同子级的抽象类的多重继承? Django

python - boolean 值到小写字符串