2016-03-06 188 views
0

我一直在玩我的代码很长一段时间了。我想用由each_div变量返回的值替换一串文本,该变量从网页返回一大堆解析值。Python如何从列表中的字符串中删除字符

def scrape_page(): 
    create_dir(project_dir) 
    page = 1 
    max_page = 10 
    while page < max_page: 
     page = page + 1 
     for each_div in soup.find_all('div',{'class':'username'}): 
      f.write(str(each_div) + "\n") 

如果我运行这段代码,它将解析来自html页面的用户名类的数据。问题是,它返回它是这样的:

<div class="username">someone_s_username</div> 

我一直在试图待办事项是剥离<div class="username"></div>部离开,因此将只返回实际的用户名,而不是HTML的。如果任何人对如何做到这一点,将是了不起的想法,谢谢

+1

难道你不能直接引用所说的div的文本内容:'each_div.string' – schwobaseggl

+0

大声笑,谢谢你甚至不知道.. – Naomi

回答

1

当然,你可以使用Python的更换方法:

for each_div in soup.find_all('div',{'class':'username'}): 
    each_div = each_div.replace('''<div class="username">''',"") 
    each_div = each_div.replace("</div>","") 
    f.write(str(each_div) + "\n") 

或者,您可以拆分的字符串获得部分你想要的:

for each_div in soup.find_all('div',{'class':'username'}): 
    each_div = each_div.split(">")[1] # everything after the first ">" 
    each_div = each_div.split("<")[0] # everything before the other "<" 
    f.write(str(each_div) + "\n") 

哦,我只记得,我相信你可以可以简单地这样做:

for each_div in soup.find_all('div',{'class':'username'}): 
    f.write(str(each_div.text) + "\n") 
+0

谢谢! @schwobaseggl早些时候评论过,但由于这是一条评论,所以我会将你的答案标记为无论如何 – Naomi