2016-07-24 23 views
0

如何从绝对URL和相对URL获得绝对URL?相对URL来自链接的href试图将两个URL一起添加到一个URL

这是我的尝试:

import urllib 
import urllib.request 
import requests 
from urllib.parse import urljoin 
from bs4 import BeautifulSoup 

mainurl = "http://www.bestbuy.ca" 
theurl = "http://www.bestbuy.ca/en-CA/category/top-freezer-  refrigerators/34734.aspx?type=product&page=1&pageSize=96" 
thepage = urllib.request.urlopen(theurl) 
soup = BeautifulSoup(thepage, "html.parser") 

producturl = soup.find('h4',{"class":"prod-title"}).find('a') 

print (producturl) 

fullurl = (mainurl,producturl) 

print(fullurl) 
+0

请提供mainurl'和'producturl'的'一个例子,因为这似乎是字符串连接的任务,而不是具体到URL。 – albert

+0

输出为Insignia“('http://www.bestbuy.ca','Insignia 30'18 Cu。Ft。Top Freezer冰箱(NS-RTM18WH7-C) - 白色')”我需要整件事主要网址是“http://www.bestbuy.ca,产品网址是基于在课程标题中找到的网址。 – nobb666

+0

mainurl给出:“http://www.bestbuy.ca”和producturl是一个汤对象:Insignia 30" 18 Cu. Ft. Top Freezer Refrigerator (NS-RTM18WH7-C) - White

回答

0

您应该使用[ 'href' 属性] beautifulsoup对象上,以获得链接字符串。然后只是concatanate。

fullurl = mainurl + soup.find('h4',{"class":"prod-title"}).find('a')['href'] 

fullurl = mainurl + producturl['href'] 
+0

这是完美的。谢谢 – nobb666

1

正如@ keiv.fly已经发布,你需要获得一个链接的hrefattribute value。然后,而不是常规字符串连接,请使用.urljoin()将基础URL与链接的相对URL组合以生成绝对URL。

我也想提高你定位链接的方式:

from urllib.parse import urljoin 

product_url = soup.select_one('h4.prod-title a')["href"] 
product_url = urljoin(mainurl, product_url) 
相关问题