下面分享个scrapy的例子

利用scrapy爬取HBS 船公司柜号信息

1、前期准备

查询提单号下的柜号有哪些,主要是在下面的网站上,输入提单号,然后点击查询

https://www.hamburgsud-line.com/liner/en/liner_services/ecommerce/track_trace/index.html

通过浏览器的network,我们可以看到,请求的是如下的网址

请求的参数如下,可以看到其中一些参数是固定的,一些是变化的(下图红框中的数据),而这些变化的参数大部分是在页面上,我们可以先请求一下这个页面,获取其中提交的参数,然后再提交

2编写爬虫

 2.1首先,我们请求一下这个页面,然后获取其中的一些变化的参数,把获取到的参数组合起来


# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request, FormRequest class HbsSpider(scrapy.Spider):
name = "hbs"
allowed_domains = ["www.hamburgsud-line.com"]
def start_requests(self):
yield Request(self.post_url, callback=self.post)
def post(self, response):
sel = response.css('input')
keys = sel.xpath('./@name').extract()
values = sel.xpath('./@value').extract()
inputData = dict(zip(keys, values))

2.2 再次请求数据

1、把固定不变的参数和页面获取到的参数一起提交

2、再把header伪装一下

    post_url = 'https://www.hamburgsud-line.com/linerportal/pages/hsdg/tnt.xhtml'
def post(self, response):
sel = response.css('input')
keys = sel.xpath('./@name').extract()
values = sel.xpath('./@value').extract()
inputData = dict(zip(keys, values))
# 提交页面的解析函数,构造FormRequest对象提交表单 fd = {'javax.faces.partial.ajax': 'true',
'javax.faces.source': 'j_idt6:searchForm:j_idt8:search-submit',
'javax.faces.partial.execute': 'j_idt6:searchForm',
'javax.faces.partial.render': 'j_idt6:searchForm',
'j_idt6:searchForm:j_idt8:search-submit': 'j_idt6:searchForm:j_idt8:search-submit',
# 'j_idt6:searchForm': 'j_idt6:searchForm',
'j_idt6:searchForm:j_idt8:inputReferences': self.blNo,
# 'j_idt6:searchForm:j_idt8:inputDateFrom_input': '04-Jan-2019',
# 'j_idt6:searchForm:j_idt8:inputDateTo_input': '16-Mar-2019',
# 'javax.faces.ViewState': '-2735644008488912659:3520516384583764336'
} fd.update(inputData) headers = {
':authority': 'www.hamburgsud-line.com',
':method': 'POST',
':path': '/linerportal/pages/hsdg/tnt.xhtml',
':scheme':'https',
# 'accept': 'application/xml,text/xml,*/*;q=0.01',
# 'accept-language':'zh-CN,zh;q=0.8',
'content-type':'application/x-www-form-urlencoded; charset=UTF-8',
'faces-request': 'partial/ajax',
'origin':'https://www.hamburgsud-line.com',
'referer':'https://www.hamburgsud-line.com/linerportal/pages/hsdg/tnt.xhtml',
'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
'x-requested-with':'XMLHttpRequest'
} yield FormRequest.from_response(response, formdata=fd,callback=self.parse_post,headers=headers)

3、解析数据

3.1我们可以看到返回的数据是在XML的CDATA下,第一步,我们从中先把这个form获取出来,

    def parse_post(self, response):
# 提交成功后,继续爬取start_urls 中的页面
text = response.text;
xml_data = minidom.parseString(text).getElementsByTagName('update')
if len(xml_data) > 0:
# form = xml_data[0].textContent
form = xml_data[0].firstChild.wholeText

3.2我们定位到柜的元素里面,因为经常一个提单下会有很多柜,如果直接用网站自动生成的id号去查找,后面用其他的提单号去爬取的时候,解析可能就有问题了

所以我们不用id去定位,改为其他方式

selector = Selector(text=form)
trs = selector.css("table[role=grid] tbody tr")
for i in range(len(trs)):
print(trs[i])
td = trs[i].css("td:nth-child(2)>a::text")
yield {
'containerNo' : td.extract()
}

4、运行

>scrapy crawl hbs -o hbs.json

可以看到,爬取到的数据如下

PS:记得把设置里面的ROBOT协议改成False,否则可能失败

ROBOTSTXT_OBEY = False

5.代码

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request, FormRequest
from xml.dom import minidom
from scrapy.selector import Selector class HbsSpider(scrapy.Spider):
name = "hbs"
allowed_domains = ["www.hamburgsud-line.com"]
#start_urls = ['https://www.hamburgsud-line.com/linerportal/pages/hsdg/tnt.xhtml'] def __init__(self, blNo='SUDU48AKL0271001', *args, **kwargs):
self.blNo = blNo # ----------------------------提交---------------------------------
# 提交页面的url
post_url = 'https://www.hamburgsud-line.com/linerportal/pages/hsdg/tnt.xhtml' def start_requests(self):
yield Request(self.post_url, callback=self.post) def post(self, response):
sel = response.css('input')
keys = sel.xpath('./@name').extract()
values = sel.xpath('./@value').extract()
inputData = dict(zip(keys, values))
# 提交页面的解析函数,构造FormRequest对象提交表单 if "j_idt6:searchForm" in inputData:
fd = {'javax.faces.partial.ajax': 'true',
'javax.faces.source': 'j_idt6:searchForm:j_idt8:search-submit',
'javax.faces.partial.execute': 'j_idt6:searchForm',
'javax.faces.partial.render': 'j_idt6:searchForm',
'j_idt6:searchForm:j_idt8:search-submit': 'j_idt6:searchForm:j_idt8:search-submit',
# 'j_idt6:searchForm': 'j_idt6:searchForm',
'j_idt6:searchForm:j_idt8:inputReferences': self.blNo,
# 'j_idt6:searchForm:j_idt8:inputDateFrom_input': '04-Jan-2019',
# 'j_idt6:searchForm:j_idt8:inputDateTo_input': '16-Mar-2019',
# 'javax.faces.ViewState': '-2735644008488912659:3520516384583764336'
}
else:
fd = {'javax.faces.partial.ajax': 'true',
'javax.faces.source': 'j_idt7:searchForm: j_idt9:search - submit',
'javax.faces.partial.execute': 'j_idt7:searchForm',
'javax.faces.partial.render': 'j_idt7:searchForm',
'j_idt7:searchForm:j_idt9:search-submit': 'j_idt7:searchForm:j_idt9:search-submit',
# 'javax.faces.ViewState:': '-1349351850393148019:-4619609355387768827',
# 'j_idt7:searchForm:': 'j_idt7:searchForm',
# 'j_idt7:searchForm:j_idt9:inputDateFrom_input':'13-Dec-2018',
# 'j_idt7:searchForm:j_idt9:inputDateTo_input':'22-Feb-2019',
'j_idt7:searchForm:j_idt9:inputReferences': self.blNo
} fd.update(inputData) headers = {
':authority': 'www.hamburgsud-line.com',
':method': 'POST',
':path': '/linerportal/pages/hsdg/tnt.xhtml',
':scheme':'https',
# 'accept': 'application/xml,text/xml,*/*;q=0.01',
# 'accept-language':'zh-CN,zh;q=0.8',
'content-type':'application/x-www-form-urlencoded; charset=UTF-8',
'faces-request': 'partial/ajax',
'origin':'https://www.hamburgsud-line.com',
'referer':'https://www.hamburgsud-line.com/linerportal/pages/hsdg/tnt.xhtml',
'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
'x-requested-with':'XMLHttpRequest'
} yield FormRequest.from_response(response, formdata=fd,callback=self.parse_post,headers=headers) def parse_post(self, response):
# 提交成功后,继续爬取start_urls 中的页面
text = response.text;
xml_data = minidom.parseString(text).getElementsByTagName('update')
if len(xml_data) > 0:
# form = xml_data[0].textContent
form = xml_data[0].firstChild.wholeText selector = Selector(text=form)
trs = selector.css("table[role=grid] tbody tr")
for i in range(len(trs)):
print(trs[i])
td = trs[i].css("td:nth-child(2)>a::text")
yield {
'containerNo' : td.extract()
}

python scrapy爬取HBS 汉堡南美航运公司柜号信息的更多相关文章

  1. Python——Scrapy爬取链家网站所有房源信息

    用scrapy爬取链家全国以上房源分类的信息: 路径: items.py # -*- coding: utf-8 -*- # Define here the models for your scrap ...

  2. Python scrapy爬取带验证码的列表数据

    首先所需要的环境:(我用的是Python2的,可以选择python3,具体遇到的问题自行解决,目前我这边几百万的数据量爬取) 环境: Python 2.7.10 Scrapy Scrapy 1.5.0 ...

  3. 使用python scrapy爬取知乎提问信息

    前文介绍了python的scrapy爬虫框架和登录知乎的方法. 这里介绍如何爬取知乎的问题信息,并保存到mysql数据库中. 首先,看一下我要爬取哪些内容: 如下图所示,我要爬取一个问题的6个信息: ...

  4. python scrapy 爬取西刺代理ip(一基础篇)(ubuntu环境下) -赖大大

    第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrapy框架 具体就自行百度了,主要内容不是在这. 第二步:创建scrapy(简单介绍) 1.Creating a p ...

  5. python scrapy爬取知乎问题和收藏夹下所有答案的内容和图片

    上文介绍了爬取知乎问题信息的整个过程,这里介绍下爬取问题下所有答案的内容和图片,大致过程相同,部分核心代码不同. 爬取一个问题的所有内容流程大致如下: 一个问题url 请求url,获取问题下的答案个数 ...

  6. Python Scrapy 爬取煎蛋网妹子图实例(二)

    上篇已经介绍了 图片的爬取,后来觉得不太好,每次爬取的图片 都在一个文件下,不方便区分,且数据库中没有爬取的时间标识,不方便后续查看 数据时何时爬取的,所以这里进行了局部修改 修改一:修改爬虫执行方式 ...

  7. Python Scrapy 爬取煎蛋网妹子图实例(一)

    前面介绍了爬虫框架的一个实例,那个比较简单,这里在介绍一个实例 爬取 煎蛋网 妹子图,遗憾的是 上周煎蛋网还有妹子图了,但是这周妹子图变成了 随手拍, 不过没关系,我们爬图的目的是为了加强实战应用,管 ...

  8. python+scrapy 爬取西刺代理ip(一)

    转自:https://www.cnblogs.com/lyc642983907/p/10739577.html 第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrap ...

  9. python scrapy爬取前程无忧招聘信息

    使用scrapy框架之前,使用以下命令下载库: pip install scrapy -i https://pypi.tuna.tsinghua.edu.cn/simple 1.创建项目文件夹 scr ...

随机推荐

  1. Python——微信数据分析

    数据可视化:http://echarts.baidu.com/echarts2/doc/example.html import refrom wxpy import *import jiebaimpo ...

  2. VUE:条件渲染和列表渲染

    条件渲染 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <titl ...

  3. shiro + maven 的web配置(不整合spring)

    本文采用的是1.4.0版本的shiro 官方中说的1.2之前,和之后的shiro配置分别为: 1.2之前: <filter> <filter-name>iniShiroFilt ...

  4. HDU 5228 ZCC loves straight flush( BestCoder Round #41)

    题目链接:pid=5228">ZCC loves straight flush pid=5228">题面: pid=5228"> ZCC loves s ...

  5. Cocos2d-x可以实现的动画效果

    动作(Actions)move移动:moveto/moveby 从一个位置移动到另外一个位置 从一个位置移动多少数量级rotate旋转:rotateto/rotateby 从一个角度旋转到另外一个角度 ...

  6. Math类概述及其成员方法

    Math 类包括用于运行基本数学运算的方法,如初等指数.对数.平方根和三角函数,这个类寻常开发中用的不多,可是在某些需求上会用到,比方求二个用户年龄的相差多少岁,这会用到Math类中的方法!如今把Ma ...

  7. m_Orchestrate learning system---十一、thinkphp查看临时文件的好处是什么

    m_Orchestrate learning system---十一.thinkphp查看临时文件的好处是什么 一.总结 一句话总结:可以知道thinkphp的标签被smarty引擎翻译而来的php代 ...

  8. xBIM 基础05 3D墙案例

    系列目录    [已更新最新开发文章,点击查看详细]  使用编码的形式去生成一堵墙的模型需要做很多的工作. using System; using System.Collections.Generic ...

  9. Kettle的四大不同环境工具

    不多说,直接上干货! kettle里有不同工具,分别用于ETL的不同阶段. 初学者,建议送Spoon开始.高手,是四大工具都会用. Sqoop: 图形界面工具,快速设计和维护复杂的ETL工作流.集成开 ...

  10. 编程语言与Python学习(二)

    1.1 流程控制之for循环 1 迭代式循环:for,语法如下 for i in range(10): 缩进的代码块 2 break与continue(同上) 3 循环嵌套 for i in rang ...