我正在尝试从http://portal.uspto.gov/EmployeeSearch/网站抓取数据。 我在浏览器中打开网站,点击网站搜索组织部分内的搜索按钮,查找发送给服务器的请求。
当我在我的程序中使用python请求库发布相同的请求时,我没有得到我期望的结果页面,但是我得到了相同的搜索页面,没有员工数据。 我尝试过所有变种,似乎没什么用。
我的问题是,我应该在请求中使用哪个网址,是否需要指定标题(还可以根据请求在Firefox开发人员工具中查看已复制的标题)或其他内容?
以下是发送请求的代码:
import requests
from bs4 import BeautifulSoup
def scrape_employees():
URL = 'http://portal.uspto.gov/EmployeeSearch/searchEm.do;jsessionid=98BC24BA630AA0AEB87F8109E2F95638.prod_portaljboss4_jvm1?action=displayResultPageByOrgShortNm¤tPage=1'
response = requests.post(URL)
site_data = response.content
soup = BeautifulSoup(site_data, "html.parser")
print(soup.prettify())
if __name__ == '__main__':
scrape_employees()
答案 0 :(得分:3)
action
是您向服务器发帖的网址。
input
是您需要发布到服务器的数据。 {name:value}
import requests, bs4, urllib.parse,re
def make_soup(url):
r = requests.get(url)
soup = bs4.BeautifulSoup(r.text, 'lxml')
return soup
def get_form(soup):
form = soup.find(name='form', action=re.compile(r'OrgShortNm'))
return form
def get_action(form, base_url):
action = form['action']
# action is reletive url, convert it to absolute url
abs_action = urllib.parse.urljoin(base_url, action)
return abs_action
def get_form_data(form, org_code):
data = {}
for inp in form('input'):
# if the value is None, we put the org_code to this field
data[inp['name']] = inp['value'] or org_code
return data
if __name__ == '__main__':
url = 'http://portal.uspto.gov/EmployeeSearch/'
soup = make_soup(url)
form = get_form(soup)
action = get_action(form, url)
data = get_form_data(form, '1634')
# make request to the action using data
r = requests.post(action, data=data)