网页抓取数据百度百科( 运行结果:什么样获取百度百科页面:name属性的问题 )

优采云 发布时间: 2021-11-03 02:09

  网页抓取数据百度百科(

运行结果:什么样获取百度百科页面:name属性的问题

)

  # coding=utf-8

import urllib

import urllib2

#url地址

#url=‘https://www.baidu.com/s‘

url=‘http://www.baidu.com/s‘

#参数

values={

‘ie‘:‘UTF-8‘,

‘wd‘:‘test‘

}

#进行参数封装

data=urllib.urlencode(values)

#组装完整url

#req=urllib2.Request(url,data)

url=url+‘?‘+data

#访问完整url

#response = urllib2.urlopen(req)

response = urllib2.urlopen(url)

html=response.read()

print html

  再次运行即可实现正常访问

  

  根据输入关键词获取百度百科页面:

  根据上面的参考资料可以看到,在使用get方法时,传输的数据直接显示在url地址栏中,可以快速为其设置参数实现访问:

  values={

‘ie‘:‘UTF-8‘,

‘wd‘:‘test‘

}

  但是在使用百度百科时,输入条目后传递的参数不会显示在地址栏中,那么问题来了,你怎么知道传递什么样的参数呢?通过分析百度的源代码:

  

  从上图中,您可以找到“百度点击”按钮。相应地,您可以找到输入框。可以看到get方法传递的参数'wd'就是输入框的name属性。那么,只要找到百度百科搜索框的位置,并得到其name属性的名称,就可以知道传递什么样的参数了:

  

  从图中可以看出name属性的值为“word”,因此我们可以设置参数如下:

  values = {

'word':input #其中input为用户输入

}

  在百度百科页面按F12查看请求地址、请求方法等。

  

  这个可以分析url地址并设置url=''

  请求方法是 GET 方法。

  所以读取输入条目对应的页面的代码是:

  import urllib

import urllib2

url = 'http://baike.baidu.com/search/word?'

input = raw_input("enter:")

values = {

'word':input

}

data = urllib.urlencode(values)

url = url + data

response = urllib2.urlopen(url)

html = response.read()

file = open('ex2.html','w')

file.write(html.strip())

file.close()

  程序运行结果:

  

  获取文字介绍

  由于嵌套标签的问题,处理起来比较麻烦:

  

  可以参考python官方文档中BeautifulSoup的介绍:

  

  import urllib

import urllib2

#import re

from bs4 import BeautifulSoup

url = 'http://baike.baidu.com/search/word?'

input = raw_input("enter:")

values = {

'word':input

}

data = urllib.urlencode(values)

url = url + data

response = urllib2.urlopen(url)

html = response.read()

file = open('ex2.html','w')

file.write(html.strip())

file.close()

soup= BeautifulSoup(html,"html.parser")

tags = soup.find_all("div",attrs={"class": "para"})

for tag in tags:

for string in tag.stripped_strings:

print((string)),

  操作结果:

  

  抓取第一段并将其存储在数据库中

  ex2.py文件

#-*- coding:utf-8 -*-

import urllib

import urllib2

from bs4 import BeautifulSoup

from DB import DBCLASS

#https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

def getTag(url):

response = urllib2.urlopen(url)

soup= BeautifulSoup(response,"html.parser")

tags = soup.find_all("div")

#text = soup.find_all("div",attrs={"class": "para"})

#divide = soup.find("div",{"class":"configModuleBanner"})

str = ""

for tag in tags:

#print tag['class'] Error

if tag.get('class') == [u'configModuleBanner']:

return str

elif tag.get('class') == [u'para']:

for item in tag.contents:

str =str + item.string

print item.string,

print ""

str += "\n"

else:

continue

if __name__ == '__main__':

url = 'http://baike.baidu.com/search/word?'

db = DBCLASS()

input = raw_input("enter:")

insertvalue = []

while input != "quit":

values = {

'word': input

}

data = urllib.urlencode(values)

str = getTag(url + data)

insertvalue.append((input,str))

input = raw_input("enter:")

db.insertValue(insertvalue)

  DB.py文件

import sqlite3

class DBCLASS:

def __init__(self):

self.cx = sqlite3.connect("baike.db")

self.cx.text_factory = str

self.cu = self.cx.cursor()

# self.cu.execute("drop table if exists discription")

# self.cu.execute("create table discription(word text primary key ,first_para text)")

def insertValue(self,insertvalue ):

for value in insertvalue:

self.cu.execute("insert into discription (word,first_para)values(?,?)",value)

self.cx.commit()

  操作结果:

  

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线