Python 如何从列表中的字符串中删除字符
Python How to remove characters from a string inside a list
我研究我的代码已经有一段时间了。我想用 each_div
变量替换值 return 中的一串文本,该变量 return 是网页中的一大堆解析值。
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 页面的用户名 class 的数据。问题是它 return 是这样的:
<div class="username">someone_s_username</div>
我一直在尝试做的是去掉 <div class="username">
和 </div>
部分,这样它只会 return 实际用户名而不是 html。如果有人知道如何实现这一点,那就太好了,谢谢
当然,您可以使用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")
我研究我的代码已经有一段时间了。我想用 each_div
变量替换值 return 中的一串文本,该变量 return 是网页中的一大堆解析值。
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 页面的用户名 class 的数据。问题是它 return 是这样的:
<div class="username">someone_s_username</div>
我一直在尝试做的是去掉 <div class="username">
和 </div>
部分,这样它只会 return 实际用户名而不是 html。如果有人知道如何实现这一点,那就太好了,谢谢
当然,您可以使用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")