繁体   English   中英

从一串html数据中提取网址

[英]Extract urls from a string of html data

我已经尝试过使用BeautifulSoup提取此html数据,但仅受标签限制。 我需要做的是在前缀www.example.com/products/之后获得尾随的something.htmlsome/something.html ,同时消除诸如?search=1类的参数。 我更喜欢使用正则表达式,但是我不知道确切的模式。

输入:

System","urlKey":"ppath","value":[],"hidden":false,"locked":false}],"bizData":"Related+Categories=Mobiles","pos":0},"listItems":[{"name":"Sam-Sung B309i High Precision Smooth Keypad Mobile Phone ","nid":"250505808","icons":[],"productUrl":"//www.example.com/products/sam-sung-b309i-high-precision-smooth-keypad-mobile-phone-i250505808-s341878516.html?search=1", "image": ["//www.example.com/products/site/ammaxxllx.html], "https://www.example.com/site/kakzja.html

prefix = "www.example.com/products/"
# do something
# expected output: ['sam-sung-b309i-high-precision-smooth-keypad-mobile-phone-i250505808-s341878516.html', 'site/ammaxxllx.html']

我想您想在这里使用re一个小技巧,因为我“?” 将遵循URI中的“ html”:

import re 

L = ["//www.example.com/products/ammaxxllx.html", "https://www.example.com/site/kakzja.html", "//www.example.com/products/sam-sung-b309i-high-precision-smooth-keypad-mobile-phone-i250505808-s341878516.html?search=1"]
prefix = "www.example.com/products/"

>>> [re.search(prefix+'(.*)html', el).group(1) + 'html' for el in L if prefix in el]
['ammaxxllx.html', 'sam-sung-b309i-high-precision-smooth-keypad-mobile-phone-i250505808-s341878516.html']

尽管以上使用re模块的答案都很棒。 您也可以不使用该模块而变通。 像这样:

prefix = 'www.example.com/products/'
L = ['//www.example.com/products/sam-sung-b309i-high-precision-smooth-keypad-mobile-phone-i250505808-s341878516.html?search=1', '//www.example.com/products/site/ammaxxllx.html', 'https://www.example.com/site/kakzja.html']
ans = []
for l in L:
    input_ = l.rsplit(prefix, 1)
    try:
        input_ = input_[1]
        ans.append(input_[:input_.index('.html')] + '.html')
    except Exception as e:
        pass
print ans
['sam-sung-b309i-high-precision-smooth-keypad-mobile-phone-i250505808-s341878516.html', 'site/ammaxxllx.html']

另一种选择是使用urlparse代替/与re一起使用

它将允许您分割这样的URL:

import urlparse

my_url = "http://www.example.com/products/ammaxxllx.html?spam=eggs#sometag"
url_obj = urlparse.urlsplit(my_url)

url_obj.scheme
>>> 'http'
url_obj.netloc
>>> 'www.example.com'
url_obj.path
>>> '/products/ammaxxllx.html'
url_obj.query
>>> 'spam=eggs'
url_obj.fragment
>>> 'sometag'

# Now you're able to work with every chunk as wanted! 
prefix = '/products'
if url_obj.path.startswith(prefix):
    # Do whatever you need, replacing the initial characters. You can use re here
    print url_obj.path[len(prefix) + 1:]
>>>> ammaxxllx.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM