python - 使用 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',
...}
解决方案
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
是一个集合,如果它在那里,它将删除它,如果它不存在,则什么也不做。
推荐阅读
- apache - 如何使用 Apache Lucenes Indexer 搜索来搜索日语单词?
- css - 如何创建如图所示的响应式网格设计?
- jira - 一个项目 JIRA Ticket 中的更改如何反映另一个项目中的链接工单
- sql - 在红移中将日期转换为 DD-MMM-YY
- user-interface - Octave GUI 开发
- windows - 将 wxWidgets 与 MinGW、CMake 和 Code::Blocks 一起使用
- c# - 在 asp.net 中获取客户端 Windows 用户 ID,用于 LDAP 单点登录
- node.js - 多个 RESTful API 服务的 NodeJS 身份验证
- go - 为什么 %T 不打印我的常量的类型?
- materialize - 是否可以覆盖物化 css navbar 的行为并使其成为引导样式?