
从网站提取网址时如何去除括号和单引号?
在使用 python 爬取网站时,有时会遇到从 html 代码中提取的网址被括号或单引号包裹的情况。以下是一个使用 lxml 和 requests 模块去除这些符号的解决方案:
import requests
from lxml import etree
url = 'http://www.prnasia.com/m/mediafeed/rss?id=2303&t=240'
# 设置 HTTP 请求头
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'}
# 发送 HTTP GET 请求
res = requests.get(url, headers=headers)
# 将 HTML 响应解析为 DOM 树
res_dome = etree.HTML(res.text)
# 使用 XPath 提取网址
hrefs = res_dome.xpath('//h3/a/@href')
# 移除括号和单引号
cleaned_hrefs = [href.replace('(', '').replace(')', '').replace("'", "") for href in hrefs]
print(cleaned_hrefs)这样,您将得到一个包含所有提取网址(无括号或单引号)的列表。










