Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

python - BeautifulSoup - stripping out non-breaking spaces from HTML

I am trying to scrape a number of 10K Risk Factor sections, e.g. https://www.sec.gov/Archives/edgar/data/1321502/000143774910004615/andain_10k-123106.htm

One of my problems is that I'm trying to match a few strings exactly (such as "Risk Factors") but sometimes there are several non-breaking spaces between the words

I am hoping I can just strip them out as they're not useful to me, so I tried:

url = 'https://www.sec.gov/Archives/edgar/data/1321502/000143774910004615/andain_10k-123106.htm'
page = requests.get(url)
soup = BeautifulSoup(page.text.replace("xa0"," "), 'html.parser')

And then searching the soup (in the usual way) to test whether it worked:

soup.find_all(string="ITEM 1A.xa0xa0RISK FACTORS")

But the output still contains non-breaking spaces, which it shouldn't:

Out[42]: ['ITEM 1A.xa0xa0RISK FACTORS']

What am I doing wrong?

question from:https://stackoverflow.com/questions/65829163/beautifulsoup-stripping-out-non-breaking-spaces-from-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

import requests
from bs4 import BeautifulSoup

url = 'https://www.sec.gov/Archives/edgar/data/1321502/000143774910004615/andain_10k-123106.htm'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
cleaned_up = [
    i.getText(strip=True).replace(u"xa0", " ")
    for i in soup.find_all("font") if i.getText().startswith("ITEM")
]
print(cleaned_up[1])

Output:

ITEM 1A.  RISK FACTORS

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...