2017-03-05 51 views
3

我試圖從http://portal.uspto.gov/EmployeeSearch/網站上搜索數據。 我在瀏覽器中打開網站,點擊網站搜索組織部分中的搜索按鈕,然後查找發送到服務器的請求。Python發佈美國專利商標局網站申請要求

當我在我的程序中使用python requests library發佈相同的請求時,我沒有得到我期待的結果頁面,但我得到了相同的搜索頁面,沒有員工數據。 我試過所有的變種,似乎沒有任何工作。

我的問題是,我應該在我的請求中使用哪個URL,是否需要指定頭文件(也可以嘗試,在請求時在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&currentPage=1' 

    response = requests.post(URL) 

    site_data = response.content 
    soup = BeautifulSoup(site_data, "html.parser") 
    print(soup.prettify()) 


if __name__ == '__main__': 
scrape_employees() 
+0

如果可能的話,您應該使用API​​而不是屏幕抓取。美國專利商標局的API被記錄在[這裏](https://developer.uspto.gov/api-catalog)。 – ThisSuitIsBlackNot

+0

感謝您的建議@ThisSuitIsBlackNot。不幸的是,我無法從美國專利商標局的API獲取我需要的所有數據(員工姓名)...... – narog

+0

這太糟糕了。無論如何,它看起來像忘了把'orgShortNm = foo'放在請求體中。 – ThisSuitIsBlackNot

回答

3

所有你需要的數據是在form標籤:enter image description here

action是URL,當你發表的帖子中的服務器。

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) 
+2

謝謝宏傑李,它工作出色!乾杯! – narog