首页 > 解决方案 > 删除部分href链接?

问题描述

我正在抓取 Google 搜索结果。这是我的代码部分。

def select_wholePage(driver):
    items = driver.find_elements_by_xpath('//*[@id="main"]/div')
    assert isinstance(items, object)
    return items


def get_result(item_in):
    try:
        title = item_in.find_element_by_xpath('.//div/div/a/h3/div').text
        print(title)
    except exceptions.NoSuchElementException:
        return
    try:
        link = item_in.find_element_by_xpath('.//div/div/a').get_attribute('href')
        print(link)
    except exceptions.NoSuchElementException:
        return
    result = (title, link)
    return result

输出 -> 我可以获得所需的元素,但是当我打印链接时,会附加“https://www.google.com/url?q=”,如下所示。"https://www.google.com/url?q=" 在此处输入图像描述

如何删除它?

标签: pythonweb-scraping

解决方案


如果https://www.google.com/url?q=是固定的并且始终存在的.replace方法就足够了,即:

encased = "https://www.google.com/url?q=https://www.example.com"
core = encased.replace("https://www.google.com/url?q=", "", 1)
print(core)

输出

https://www.example.com

我提供了第三个论点,将.replace其限制为最多 1 个替换,以防https://www.google.com/url?q=出现进一步的情况。


推荐阅读