【问题标题】:Is there another way besides "strip()" and "replace()" to get rid of the extra white space in the data I scraped?除了“strip()”和“replace()”之外,还有其他方法可以消除我抓取的数据中的额外空白吗?
【发布时间】: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


【解决方案1】:

您应该使用列表推导:

deaths = [s.strip() for s in deaths]

但是,这里有很多不必要的中间步骤 - 您可以直接使用 find_all 之外的列表推导:

deaths = [hit.contents[0].strip() for hit in soup.find_all('div', class_="headline")]

使用给定的网站和查询,deaths 将是

['Will', 'Jon Arryn', 'Jory Cassel', 'Benjen Stark', 'Robert Baratheon', 'Syrio Forel', 'Eddard Stark', 'Viserys Targaryen', 'Drogo', 'Rhaego', 'Mirri Maz Duur', 'Rakharo', 'Yoren', 'Renly Baratheon', 'Rodrik Cassel', 'Irri', 'Maester Luwin', 'Qhorin', 'Pyat Pree', 'Doreah', 'Xaro Xhoan Daxos', 'Hoster Tully', 'Jeor Mormont', 'Craster', 'Kraznys', 'Beric Dondarrion', 'Ros', 'Talisa Stark', 'Robb Stark', 'Catelyn Stark', 'Polliver', 'Tansy', 'Joffrey Baratheon', 'Karl Tanner', 'Locke', 'Rast', 'Lysa Arryn', 'Oberyn Martell', 'The Mountain', 'Grenn', 'Mag the Mighty', 'Pyp', 'Styr', 'Ygritte', 'Jojen Reed', 'Shae', 'Tywin Lannister', 'Mance Rayder', 'Janos Slynt', 'Barristan Selmy', 'Maester Aemon', 'Karsi', 'Shireen Baratheon', 'Hizdahr zo Loraq', 'Selyse Baratheon', 'Stannis Baratheon', 'Myranda', 'Meryn Trant', 'Myrcella Baratheon', 'Jon Snow', 'Areo Hotah', 'Doran Martell', 'Trystane Martell', 'The Flasher', 'Roose Bolton', 'Walda Bolton', 'Unnamed Bolton Child', 'Balon Greyjoy', 'Alliser Thorne', 'Olly', 'Ser Arthur Dayne', 'Osha', 'Khal Moro', 'Three-Eyed Raven', 'Leaf', 'Hodor', 'Aerys II Targaryen, "The Mad King"', 'Brother Ray', 'Lem', 'Brynden Tully (The Blackfish)', 'Lady Crane', 'The Waif', 'Razdal mo Eraz', 'Belicho Paenymion', 'Rickon Stark', 'Jon Umber', 'Wun Weg Wun Dar Wun', 'Ramsay Bolton', 'Grand Maester Pycelle', 'Lancel', 'The High Sparrow', 'Loras Tyrell', 'Mace Tyrell', 'Kevan Lannister', 'Margaery Tyrell', 'Tommen Baratheon', 'Walder Rivers', 'Lothar Frey', 'Walder Frey', 'Lyanna Stark', 'Nymeria Sand', 'Obara Sand', 'Tyene Sand', 'Olenna Tyrell', 'Randyll Tarly', 'Dickon Tarly', 'Thoros of Myr', 'Petyr "Littlefinger" Baelish', 'Ned Umber']

【讨论】:

    【解决方案2】:

    字符串是不可变的。 strip()replace() 返回新字符串,它们不会更改原始字符串。

    使用@Tomothy32 建议的列表理解:

    deaths = [hit.contents.strip() for hit in soup.find_all('div', class_="headline")]
    

    【讨论】:

      【解决方案3】:

      由于我所在的位置,我无法进行测试,但您应该能够避免这种情况,但在 anchor-only 类元素的 name 属性中使用已经干净的字符串anchor-only

      deaths = [item['name'] for item in soup.select('.anchor-only')]
      

      【讨论】:

        猜你喜欢
        • 2018-03-01
        • 2019-09-14
        • 1970-01-01
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-18
        • 1970-01-01
        相关资源
        最近更新 更多