首页 > 解决方案 > 使用 Python 3 进行网页抓取

问题描述

抓取网站后,我检索了所有 html 链接。将它们设置为 set() 后,为了删除任何重复项,我仍在检索某些值。如何从链接集中删除 '#'、'#content'、'#uscb-nav-skip-header'、'/'、None 的值。

from bs4 import BeautifulSoup
import urllib
import re

#Gets the html code for scrapping
r = urllib.request.urlopen('https://www.census.gov/programs-surveys/popest.html').read()

#Creates a beautifulsoup object to run
soup = BeautifulSoup(r, 'html.parser')

#Set removes duplicates
lst2 = set()
for link in soup.find_all('a'):
    lst2.add(link.get('href'))
lst2

{'#',
 '#content',
 '#uscb-nav-skip-header',
 '/',
 '/data/tables/time-series/demo/popest/pre-1980-county.html',
 '/data/tables/time-series/demo/popest/pre-1980-national.html',
 '/data/tables/time-series/demo/popest/pre-1980-state.html',
 '/en.html',
 '/library/publications/2010/demo/p25-1138.html',
 '/library/publications/2010/demo/p25-1139.html',
 '/library/publications/2015/demo/p25-1142.html',
 '/programs-surveys/popest/data.html',
 '/programs-surveys/popest/data/tables.html',
 '/programs-surveys/popest/geographies.html',
 '/programs-surveys/popest/guidance-geographies.html',
 None,
 'https://twitter.com/uscensusbureau',
 ...}

标签: pythonhtmlweb-scraping

解决方案


URL 中的字符#(以及它之后的所有内容)与浏览器相关,但在发出 Web 请求时与服务器无关,因此可以从 URL 中删除这些部分。这将使 URL 像'#content'空白一样,但也会'/about#contact'变为 just '/about',这实际上是您想要的。从那里,我们只需要一个if语句来只将非空字符串添加到集合中。这也会同时过滤掉None

lst2 = set()
for link in soup.find_all('a'):
    url = link.get('href')
    url = url.split('#')[0]
    if url:
        lst2.add(url)

如果你特别想排除'/'(尽管它是一个有效的 URL),你可以简单地写lst2.discard('/')在最后。由于lst2是一个集合,如果它在那里,它将删除它,如果它不存在,则什么也不做。


推荐阅读