Información del producto Crawling Dangdang
objetivos
Rastree la información del producto de Dangdang en lotes y guárdelo como un archivo csv en el archivo local.
Preparación del proyecto
Software: biblioteca de
terceros de Pycharm : solicitudes, fake_useragent, lxml, csv
Dirección del sitio web: http://search.dangdang.com/
Análisis de sitios web
Abra la página del sitio web y busque un producto, como zapatos Doudou.
puede ser visto:
http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input
clave = nombre del producto
Analizar si se trata de una página web estática.
F12 abre el modo de desarrollador.
Copie las palabras clave, Ctrl + U para ver el código fuente. Péguelo y búsquelo.
Páginas estáticas.
Análisis de número de página
http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input&page_index=1
http://search.dangdang.com/?key=%B6%B9%B6%B9 % D0% AC & act = input & page_index = 2
http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input&page_index=3
Cambiará después de que se encuentre page_index.
Análisis anti-ascenso
Múltiples accesos a la misma dirección IP correrán el riesgo de ser bloqueados. Aquí, fake_useragent se usa para generar encabezados de solicitud de usuario-agente aleatorios para el acceso.
Código
1. Importe la biblioteca de terceros correspondiente, defina una clase para heredar el objeto, defina el método init para heredar self y la función principal main para heredar self.
import requests
from fake_useragent import UserAgent
from lxml import etree
import csv
class dangdang(object):
def __init__(self):
self.url = 'http://search.dangdang.com/?key={}&page_index={}'
ua = UserAgent(verify_ssl=False)
for i in range(1, 100):
self.headers = {
'User-Agent': ua.random
}
def main(self):
pass
if __name__ == '__main__':
spider = dangdang()
spider.main()
2. Envíe una solicitud para obtener la página web.
def get_html(self,url):
response=requests.get(url,headers=self.headers)
html=response.text
return html
3. Analice la página web para obtener información del producto y guárdela localmente.
def parse_html(self,html):
target=etree.HTML(html)
titles=target.xpath('//p[@class="name"]/a/@title')
prices=target.xpath('//p[@class="price"]/span/text()')
links=target.xpath('//p[@class="name"]/a/@href')
with open('F:/pycharm文件/document/dangdang.csv','a',newline='',encoding='gb18030') as f:
csvwriter = csv.writer(f, delimiter=',')
for title,price,link in zip(titles,prices,links):
csvwriter.writerow([title,price,link])
4. Función principal y llamada de función.
def main(self):
product = str(input('请输入您要浏览的商品:'))
end_page=int(input("要爬多少页:"))
for page in range(1,end_page+1):
url = self.url.format(product,page)
print("第%s页。。。。"%page)
html=self.get_html(url)
self.parse_html(html)
print("第%s页爬取完成" % page)
Pantalla de efectos
Abra el archivo local.
El código completo es el siguiente:
import requests
from fake_useragent import UserAgent
from lxml import etree
import csv
class dangdang(object):
def __init__(self):
self.url = 'http://search.dangdang.com/?key={}&page_index={}'
ua = UserAgent(verify_ssl=False)
for i in range(1, 100):
self.headers = {
'User-Agent': ua.random
}
def get_html(self,url):
response=requests.get(url,headers=self.headers)
html=response.text
return html
def parse_html(self,html):
target=etree.HTML(html)
titles=target.xpath('//p[@class="name"]/a/@title')
prices=target.xpath('//p[@class="price"]/span/text()')
links=target.xpath('//p[@class="name"]/a/@href')
with open('F:/pycharm文件/document/dangdang.csv','a',newline='',encoding='gb18030') as f:
csvwriter = csv.writer(f, delimiter=',')
for title,price,link in zip(titles,prices,links):
csvwriter.writerow([title,price,link])
def main(self):
product = str(input('请输入您要浏览的商品:'))
end_page=int(input("要爬多少页:"))
for page in range(1,end_page+1):
url = self.url.format(product,page)
print("第%s页。。。。"%page)
html=self.get_html(url)
self.parse_html(html)
print("第%s页爬取完成" % page)
if __name__ == '__main__':
spider = dangdang()
spider.main()
Descargo de responsabilidad: solo para su propio estudio y uso de referencia.