gpt4 book ai didi

python - 如何使用 python 和 selenium 抓取弹出窗口

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:39 25 4
gpt4 key购买 nike

我正在尝试从 https://ngodarpan.gov.in/index.php/search/ 中抓取 Ngo 的数据,例如姓名、手机号码、城市等。 。它以表格形式列出了非政府组织的名称,单击每个名称就会出现一个弹出页面。在下面的代码中,我正在提取每个 NGO 的 onclick 属性。我正在发出一个 get 请求,然后发出一个 post 请求来提取数据。我尝试使用 selenium 访问它,但 json 数据没有出现。

list_of_cells = []
for cell in row.find_all('td'):
text = cell.text.replace(" ", "")
list_of_cells.append(text)
list_of_rows.append(list_of_cells)
writer=csv.writer(f)
writer.writerow(list_of_cells)

通过实现上述部分,我们可以获得所有页面表格的完整详细信息。在这个网站中有 7721 个页面。我们可以简单地更改 number_of_pages 变量。

但是我们的动机是找到 Ngo 电话号码/电子邮件 ID,这是我们单击 Ngo 名称链接后得到的主要目的。但它不是链接的 href,而是一个 api get req,后面是获取数据的 post 请求.在inspect的网络部分查找

driver.get("https://ngodarpan.gov.in/index.php/search/") # load the web page
sleep(2)
....
....
driver.find_element(By.NAME,"commit").submit()
for page in range(number_of_pages - 1):
list_of_rows = []
src = driver.page_source # gets the html source of the page
parser = BeautifulSoup(src,'html.parser')
sleep(1)
table = parser.find("table",{ "class" : "table table-bordered table-striped" })
sleep(1)
for row in table.find_all('tr')[:]:
list_of_cells = []
for cell in row.find_all('td'):
x = requests.get("https://ngodarpan.gov.in/index.php/ajaxcontroller/get_csrf")
dat=x.json()
z=dat["csrf_token"]
print(z) # prints csrf token
r= requests.post("https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info", data = {'id':'','csrf_test_name':'z'})
json_data=r.text # i guess here is something not working it is printing html text but we need text data of post request like mob,email,and here it will print all the data .
with open('data1.json', 'a') as outfile:
json.dump(json_data, outfile)
driver.find_element_by_xpath("//a[contains(text(),'»')]").click()

没有这样的错误消息,代码正在运行,但正在打印 html 内容

<html>
...
...
<body>
<div id="container">
<h1>An Error Was Encountered</h1>
<p>The action you have requested is not allowed.</p> </div>
</body>
</html>

最佳答案

通过避免使用 Selenium,这可以更快地完成。他们的网站似乎在每次请求之前不断请求 token ,您可能会发现可以跳过此操作。

以下展示如何获取包含手机号码和电子邮件地址的 JSON:

from bs4 import BeautifulSoup
import requests
import time

def get_token(sess):
req_csrf = sess.get('https://ngodarpan.gov.in/index.php/ajaxcontroller/get_csrf')
return req_csrf.json()['csrf_token']


search_url = "https://ngodarpan.gov.in/index.php/ajaxcontroller/search_index_new/{}"
details_url = "https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info"

sess = requests.Session()

for page in range(0, 10000, 10): # Advance 10 at a time
print(f"Getting results from {page}")

for retry in range(1, 10):

data = {
'state_search' : 7,
'district_search' : '',
'sector_search' : 'null',
'ngo_type_search' : 'null',
'ngo_name_search' : '',
'unique_id_search' : '',
'view_type' : 'detail_view',
'csrf_test_name' : get_token(sess),
}

req_search = sess.post(search_url.format(page), data=data, headers={'X-Requested-With' : 'XMLHttpRequest'})
soup = BeautifulSoup(req_search.content, "html.parser")
table = soup.find('table', id='example')

if table:
for tr in table.find_all('tr'):
row = [td.text for td in tr.find_all('td')]
link = tr.find('a', onclick=True)

if link:
link_number = link['onclick'].strip("show_ngif(')")
req_details = sess.post(details_url, headers={'X-Requested-With' : 'XMLHttpRequest'}, data={'id' : link_number, 'csrf_test_name' : get_token(sess)})
json = req_details.json()
details = json['infor']['0']

print([details['Mobile'], details['Email'], row[1], row[2]])
break
else:
print(f'No data returned - retry {retry}')
time.sleep(3)

这将为您提供以下类型的首页输出:

['9871249262', 'pnes.delhi@yahoo.com', 'Pragya Network Educational Society', 'S-52559, Narela, DELHI']
['9810042046', 'mathew.cherian@helpageindia.org', 'HelpAge India', '9270, New Delhi, DELHI']
['9811897589', 'aipssngo@yahoo.com', 'All India Parivartan Sewa Samiti', 's-43282, New Delhi, DELHI']

关于python - 如何使用 python 和 selenium 抓取弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com