阅读OReilly.Web.Scraping.with.Python.2015.6笔记---找出网页中所有的href

1.查找以<a>开头的所有文本,然后判断href是否在<a>里面,如果<a>里面有href,就像<a href=" " >,然后提取href的值。

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")
bsObj = BeautifulSoup(html)
for link in bsObj.findAll("a"):
    if ‘href‘ in link.attrs:
        print(link.attrs[‘href‘])

运行结果:

在网页源代码的定位:

2.提取以 /wiki/开头的文本

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")
bsObj = BeautifulSoup(html,"lxml")
for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$")):
    if ‘href‘ in link.attrs:
        print(link.attrs[‘href‘])

运行结果:

3.连环着提取不同网页以/wiki开头的文本

from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re
random.seed(datetime.datetime.now())
def getLinks(articleUrl):
    html = urlopen("http://en.wikipedia.org"+articleUrl)
    bsObj = BeautifulSoup(html,"lxml")
    return bsObj.find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))

links = getLinks("/wiki/Kevin_Bacon")
while len(links) > 0:
    newArticle = links[random.randint(0, len(links)-1)].attrs["href"]
    print(newArticle)
    links = getLinks(newArticle)

运行结果:

运行一段时间之后,会报错:远程主机强迫关闭了一个现有的连接,这是网站拒绝程序的连接吗?

时间: 2024-07-31 02:29:35

阅读OReilly.Web.Scraping.with.Python.2015.6笔记---找出网页中所有的href的相关文章

阅读OReilly.Web.Scraping.with.Python.2015.6笔记---Crawl

1.函数调用它自身,这样就形成了一个循环,一环套一环: from urllib.request import urlopen from bs4 import BeautifulSoup import re pages = set() def getLinks(pageUrl): global pages html = urlopen("http://en.wikipedia.org"+pageUrl) bsObj = BeautifulSoup(html,"lxml"

Python list去重及找出,统计重复项

http://bbs.chinaunix.net/thread-1680208-1-1.html 如何找出 python list 中有重复的项 http://www.cnblogs.com/feisky/archive/2012/12/06/2805251.html 比较容易记忆的是用内置的setl1 = ['b','c','d','b','c','a','a']l2 = list(set(l1))print l2 还有一种据说速度更快的,没测试过两者的速度差别l1 = ['b','c','d

python找出数组中第二大的数

#!usr/bin/env python #encoding:utf-8 ''''' __Author__:沂水寒城 功能:找出数组中第2大的数字 ''' def find_Second_large_num(num_list):   '''''   找出数组中第2大的数字   '''   #直接排序,输出倒数第二个数即可   tmp_list=sorted(num_list)   print 'Second_large_num is:', tmp_list[-2]   #设置两个标志位一个存储最

Web Scraping using Python Scrapy_BS4 - Introduction

What is Web Scraping This is also referred to as web harvesting and web data extraction. This is the process of automatically downloading a web page's data and extracting information from it. Benefits of Web Scraping Component of applications used fo

Python Show-Me-the-Code 第 0009 题 提取网页中的超链接

第 0009 题:一个HTML文件,找出里面的链接. 思路:对于提取网页中的超链接,先把网页内容读取出来,然后用beautifulsoup来解析是比较方便的.但是我发现一个问题,如果直接提取a标签的href,就会包含javascript:xxx和#xxx之类的,所以要对这些进行特殊处理. 0009.提取网页中的超链接.py #!/usr/bin/env python #coding: utf-8 from bs4 import BeautifulSoup import urllib import

Web Scraping with Python第一章

1. 认识urllib urllib是python的标准库,它提供丰富的函数例如从web服务器请求数据.处理cookie等,在python2中对应urllib2库,不同于urllib2,python3的urllib被分为若干子模块:urllib.request.urllib.parse.urllib.error等,urllib库的使用可以参考https://docs.python.org/3/library/urllib.html from urllib.request import urlop

Step by Step of &quot;Web scraping with Python&quot; ----Richard Lawson ---3/n

when trying the sample code of "link_crawler3.py", it will always fail with below message: /usr/bin/python3 /home/cor/webscrappython/Web_Scraping_with_Python/chapter01/link_crawler3.py Downloading:http://example.webscraping.com Downloading--2 Do

python找出字符串中每个字母出现的次数

#!/usr/bin/env python # coding=utf-8 str1 = "abcdefabcdefgghj" listStr = [] for eachStr in str1:     countStr = str1.count(eachStr)     numStr = eachStr + ":" + str(countStr)     if numStr not in listStr :         listStr.append(numStr

Python一日一练03----输出网页

要求 将以下文档作为网页模版,编程实现由用户定义网页信息并将网页输出保存 <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" \ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/199