python - 删除部分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="
如何删除它?
解决方案
如果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=
出现进一步的情况。
推荐阅读
- asp.net - 根据查询结果填充一个TextBox,并在DetailsView插入前绑定
- heroku - '--name' CLI 选项指的是什么名称?
- reactjs - 如何指定端口以在 Azure Web 应用程序中运行多个 ReactJS 应用程序?
- sql - 无法使用 LAG 功能 mysql
- sql-server - 自动下载最新的 SQL Server CU/SP?
- xml - 自定义 CMS,在 IIS 重置之前不会出现添加新文档
- asp.net-core - 400 Bad Request when trying to send api request with IFormFile in request object
- node.js - NodeJS/Socket.io 如何使用多个端口(监听器)
- javascript - 我正在尝试让此代码也复制带有颜色的样本组
- velo - 如何在 Wix 中创建下拉菜单