Python 将字符串添加到包含多个项目的匹配列表中

标签 python

我正在处理的代码是从 HTML 页面检索一个包含 2 个字段、URL 和标题的列表...

URL 无论如何都以 /URL.... 开头,并且我需要将“http://website.com ”附加到从 re.findall 返回的每个值中。

到目前为止的代码是这样的:

bsoup=bs(html)
tag=soup.find('div',{'class':'item'})
reg=re.compile('<a href="(.+?)" rel=".+?" title="(.+?)"')
links=re.findall(reg,str(tag))
*(append "http://website.com" to the href"(.+?)" field)*
return links

最佳答案

尝试:

for link in tag.find_all('a'):
    link['href'] = 'http://website.com' + link['href']

然后使用以下输出方法之一:

return str(soup) 获取应用更改后的文档。

return tag.find_all('a') 获取所有链接元素。

return [str(i) for i in tag.find_all('a')] 获取所有转换为字符串的链接元素。

现在,当您的 XML 解析器已在运行时,请不要尝试使用正则表达式解析 HTML。

关于Python 将字符串添加到包含多个项目的匹配列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467455/

相关文章:

python - 最快的计数向量器实现

python - 将文本添加到现有邮件正文中

python - 使用 Boto3 查找属于特定目标组的 EC2 实例

用于图像 url 的 Python 2.7 正则表达式

python - 以图形形式表示python字典

Python 请求抛出 SSLError

python - numpy stride_tricks.as_strided 与滚动窗口的列表理解

python动态输入,更新表

python - 在python中处理大量文件

python - 异常: Exception ('Exception caught in workbook destructor. Explicit close() may be required for workbook.' ,)