2017-06-14 64 views
0

我已阅读使用此命令网址:删除 r n开始刮

import urllib2 
from bs4 import BeautifulSoup 
req = urllib2.Request(url, headers=hdr) 
req2 = urllib2.urlopen(req) 

content = req2.read() 
soup = BeautifulSoup(content, "lxml") 

我想刮与结构的网站象下面这样:

<div class='\"companyNameWrapper\"'> 
\r\n 
<div class='\"companyName\"'> 
ACP Holding Deutschland GmbH 
</div> 
\r\n 

问题是因为斜杠,命令如

soup.findAll("div", {"class":"companyName"}): 

不起作用。我需要将汤转换为str以使用.replace('\',''),但这种类型是字符串和soup.findAll(和类似的bs4命令无效)。

有没有人有建议?

感谢

回答

0

在我看来,我会考虑使用正则表达式这个问题。例如,如果您想查找与公司类名称相匹配的元素,那么在这种情况下,我会这样做。

elements = soup.findAll(re.compile("^companyName")) 

这将给你一个列表,包含所有匹配的具体类。然后您可以通过索引或甚至访问它们。

我相信我很有帮助。

+0

我看到**正则表达式**并立即想到:https://stackoverflow.com/a/1732454/4022608。使用BS的正则表达式处理程序是好的,但:) – Baldrickk

0

你试过这样吗?

打印(item.contents [1] .find_all( “DIV”,{ “类”: “的companyName”})[0] .text.replace( '\', ''))

1

尝试做下一个:

content.replace("\r", "").replace("\t", "") 
#All replace as you need 
soup = BeautifulSoup(content, "lxml")