我正在处理的代码是从 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/