scrapy爬取动态网页
目标
用scrapy爬虫实现在网页 https://www.genealogy.math.ndsu.nodak.edu 中输入人名进行搜索,得到搜索结果网页内容。
步骤
- 观察发现搜索结果网页的url是https://www.genealogy.math.ndsu.nodak.edu/quickSearch.php,不能通过构造url获取该网页的真正信息,因此知道是动态网页。
- 查看网页 https://www.genealogy.math.ndsu.nodak.edu中的action,有如下html代码,发现目标action的方式是post,且需要通过form-data提交要搜索的人名。
<form action="quickSearch.php" method="post">
<div style="text-align: center"><label for="searchTerms">Quick Search</label>
<input name="searchTerms" type="text" size="30" maxlength="90" id="searchTerms" />
<input name="Submit" type="submit" value="Search" />
<br />
<span style="font-size: small"><a href="search.php">Advanced Search</a></span>
</div>
</form>
-
使用postman进行如下测试
-
在scrapy的spider中用如下代码提交form-data并得到响应网页内容,在函数
parse_MGP
中进行下一步爬取信息操作。
yield scrapy.FormRequest(
url=self.start_urls[1],
formdata={"searchTerms": self.searchName},
callback=self.parse_MGP
)
总结
- 不能通过构造URL获取的网页是动态网页,需要用动态网页的爬取方法。
- 通过观察网页的source文件,找到目标action的提交方式。
- 用postman进行测试。
- 用
scrapy.FormRequest()
提交有formdata的post请求。