我使用python3.5和window10。
当我抓取一些页面时,我通常使用urlopen和'for'迭代来使用url更改。像下面的代码。
from bs4 import BeautifulSoup
import urllib
f = open('Slave.txt','w')
for i in range(1,42):
html = urllib.urlopen('http://xroads.virginia.edu/~hyper/JACOBS/hjch'+str(i)+'.htm')
soup = BeautifulSoup(html,"lxml")
text = soup.getText()
f.write(text.encode("utf-8"))
f.close()
但是,我遇到了麻烦,因为网址没有变化,虽然我点击了下一页并改变了网络竞争对手,如图片。网址没有变化,没有模式。 enter image description here
网址中没有任何信号可以让网站更改。
http://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp
网站就在这里 我找到的线索是在分页课上。 我发现了下一页的一些链接,但我不知道如何使用此链接 在Beautifulsoup。我认为commonPagingPost是开发人员定义的函数。
<span class="number"><a href="javascript:;"
class="on">1</a>
<a href="javascript:commonPagingPost('2','10','Shr01_lis.jsp');">2</a>
<a href="javascript:commonPagingPost('3','10','Shr01_lis.jsp');">3</a>
<a href="javascript:commonPagingPost('4','10','Shr01_lis.jsp');">4</a>
<a href="javascript:commonPagingPost('5','10','Shr01_lis.jsp');">5</a></span>
如何使用beutifulSoup4打开或抓取所有这些网站? 当我使用urlopen时,我只是得到了fisrt页面。
答案 0 :(得分:0)
你不能单独使用beautifulsoup,因为它不支持ajax。您需要使用selenium,ghost.py或其他支持javascript的网络浏览器。
使用这些库,您将能够模拟这些链接上的点击,然后获取新加载的内容。
答案 1 :(得分:0)
我搜索了commonPagingPost
的代码并找到了这个JavaScript函数定义:
function commonPagingPost (Page, Block, Action) {
var Frm = document.mainForm;
Frm.RCEPT_NO.value = "";
Frm.page.value = Page;
Frm.action = Action;
Frm.submit ();
}
它的作用是它填补了#main;主要形式&#34;并提交它。 mainForm
看起来像什么?
<form name="mainForm" method="post" action="">
<input type="hidden" name="RCEPT_NO" value="">
<input type="hidden" name="search_flag" value="N">
<input type="hidden" name="page" value="1">
</form>
好的,该函数填写表单,将目标页面设置为&#39; Shr01_lis.jsp&#39;,与您尝试刮取的页面相同。我们可以用Python做到这一点吗?是的!
import requests
r = requests.post(
"http://eungdapso.seoul.go.kr/Shr/Shr01/Shr01_lis.jsp",
data={
"RCEPT_NO": "",
"search_flag": "N",
"page": "5"
})
soup = BeautifulSoup(r.text, 'lxml')
我更喜欢requests
而不是urllib,因为请求对于POST请求来说更简单。