从HTML中提取但不包含<h>的项目

时间:2018-11-15 11:06:42

标签: python html web-scraping beautifulsoup

我刮掉了一个向我提供里斯本邮政编码的网站。使用BeautifulSoup,我可以在一个班级项目中获取邮政编码。但是,邮政编码本身仍在其他类中,我尝试了很多方法从中提取所有邮政编码。但是,除了字符串操作外,我无法使其工作。我是webscraping和html的新手,所以很抱歉,如果这个问题很简单。

这是我的代码:

from bs4 import BeautifulSoup as soup
from requests import get

url='https://worldpostalcode.com/portugal/lisboa/'
response = get(url)
print(response.text)
html_soup = soup(response.text,'lxml')
type(html_soup)
zip_codes=html_soup.find_all('div', {'class' : 'rightc'})

这是结果的摘要,我只想从中提取邮政编码。

[<div class="rightc">1000-246<hr/> 1050-138<hr/> 1069-188<hr/> 1070-204<hr/> 1100-069<hr/> 1100-329<hr/> 1100-591<hr/> 1150-144<hr/> 1169-062<hr/> 1170-128<hr/> 1170-395<hr/> 1200-228<hr/> 1200-604<hr/> 1200-862<hr/> 1250-111<hr/> 1269-121<hr/> 1300-217<hr/> 1300-492<hr/> 1350-092<hr/> 1399-014<hr/> 1400-237<hr/> 1500-061<hr/> 1500-360<hr/> 1500-674<hr/> 1600-232<hr/> 1600-643<hr/> 1700-018<hr/> 1700-302<hr/> 1750-113<hr/> 1750-464<hr/> 1800-262<hr/> 1900-115<hr/> 1900-401<hr/> 1950-208<hr/> 1990-162<hr/> 1000-247<hr/> 1050-139<hr/> 1069-190<hr/> 1070-205<hr/> 1100-070<hr/> 1100-330</div>]

4 个答案:

答案 0 :(得分:2)

您的结果DelayTask(10, () => /* doSomeStuff...*/ ); 具有类型zip_codes,它是一组bs4.element.ResultSet。因此,bs4.element.Tag是您感兴趣的(找到的第一个标签)。使用zip_codes[0]方法剥离.text标签。现在,您有一长串邮政编码,并用空格分隔。将它们以某种方式剥离到一个列表中(下面有两个选项,第一个选项是Pythonic且速度更快)。

<hr>

输出:

from bs4 import BeautifulSoup as soup
from requests import get

url = 'https://worldpostalcode.com/portugal/lisboa/'
response = get(url)
html_soup = soup(response.text,'lxml')
zip_codes = html_soup.find_all('div', {'class' : 'rightc'})

# option one
zips = zip_codes[0].text.split(' ')
print(zips[:8])

# option two (slower)
zips = []
for zc in zip_codes[0].childGenerator():
    zips.append(zc.extract().strip())
print(zips[:8])

答案 1 :(得分:1)

html_soup = BeautifulSoup(htmlcontent,'lxml')
type(html_soup)
zip_codes=html_soup.find_all('div', {'class' : 'rightc'})

print(zip_codes[0].text.split(' '))

您可以获得textsplit

o / p:

[u'1000-246', u'1050-138', u'1069-188', u'1070-204',.........]

答案 2 :(得分:1)

使用正则表达式获取代码

from bs4 import BeautifulSoup
import requests
import re

url = 'https://worldpostalcode.com/portugal/lisboa/'
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
element = soup.select_one('.codelist .rightc')
codes = re.findall(r"\d{4}-\d{3}",element.text)

for code in codes:
    print(code)

答案 3 :(得分:1)

我建议您在将页面响应作为汤加载之前,将所有</hr>标记替换为一些delimiter (i.e., # or $ or ,)。现在,一旦将其加载到汤中,该工作将变得非常容易,您只需调用该类就可以将邮政编码提取为列表。

from bs4 import BeautifulSoup as soup
from requests import get

url='https://worldpostalcode.com/portugal/lisboa/'
response = get(url)
print(response.text.replace('<hr>', '#'))
html_soup = soup(response.text,'lxml')
type(html_soup)
zip_codes=html_soup.find_all('div', {'class' : 'rightc'})
zip_codes = zip_codes.text.split('#') 

希望这会有所帮助!干杯!

P.S .:答案是开放的,以供改进和评论。