【发布时间】:2019-04-19 22:31:14
【问题描述】:
我对 python 还很陌生,我正在尝试建立一个网络爬虫来收集有关在《权力的游戏》中死去的角色的数据。我已经得到了我想要的数据,但我似乎无法从数据中得到一些额外的绒毛。
我已经尝试了.strip() 方法和使用.replace(" ", "") 的.replace() 方法,但每次都没有任何变化。这是我的代码块:
url = "http://time.com/3924852/every-game-of-thrones-death/"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
# Find the characters who have died by searching for the text embedded within the <div> tag with class = "headline"
find_deaths = soup.find_all('div', class_="headline")
# Strip out all the extra fluff at the beginning and end of the text and add it to list
for hit in find_deaths:
deaths.append(hit.contents)
此代码在列表中生成如下所示的项目:
deaths = [['\n Will\n '], ['\n Jon Arryn\n '], ['\n Jory Cassel\n ']
我尝试了以下方法来尝试剔除数据周围的多余绒毛,但它根本不会改变列表中的任何内容。
for item in deaths:
str(item).strip()
for item in deaths:
str(item).replace("\n ", "")
使用上述两种方法中的任何一种,我认为它会从列表中的项目中去除所有多余的绒毛,但它似乎根本没有改变任何东西。
除了 strip 和 replace 之外,我还能使用另一种方法来消除这些数据中的多余绒毛。
【问题讨论】:
-
strip() 和 replace() 返回新字符串。
-
正如@Michael Butscher 所指出的,你应该做
new_item = str(item).strip然后new_item将在剥离操作后成为item的副本
标签: python html web-scraping strip