2017-04-20 7 views
1
import requests 

a = 'http://tmsearch.uspto.gov/bin/showfield?f=toc&state=4809%3Ak1aweo.1.1&p_search=searchstr&BackReference=&p_L=100&p_plural=no&p_s_PARA1={}&p_tagrepl%7E%3A=PARA1%24MI&expr=PARA1+or+PARA2&p_s_PARA2=&p_tagrepl%7E%3A=PARA2%24ALL&a_default=search&f=toc&state=4809%3Ak1aweo.1.1&a_search=Submit+Query' 
a = a.format('coca-cola') 

b = requests.get(a) 

print(b.text) 
print(b.url) 

印刷されたURLをコピーしてブラウザに貼り付けると、サイトは問題なく開きますが、requests.getを実行するとトークンが表示されますか?エラー。何か私にできることはありますか?Pythonのリクエストでエラーが返され、リンクを手動で開くと完全に開きます

VIA requests.get私は元に戻りますが、手動で行うとデータはありません。それは言う:<html><head><TITLE>TESS -- Error</TITLE></head><body>

+0

ありがとう、それを修正しました –

+1

私にとって「この検索セッションは終了しました」と返されます。 Pythonのコードだけでなく、ブラウザにも表示されます。ほとんどの場合、検索エンジンはヘッダーで指定されたトークンを使用します。 [ネットワーク]タブ(クロム)にヘッダーが表示されます。 – soon

+0

すぐにコカコーラをペプシなどに変更しても? –

答えて

0

まず、あなたのウェブサイトの利用規約と使用ポリシーに従ってください。

これは少し複雑に見えるかもしれません。あなたは[web-scraping session] [1]を通じて特定のstateを維持する必要があります。そして、あなたは道に沿ってBeautifulSoupのように、HTMLパーサが必要になります:

from urllib.parse import parse_qs, urljoin 

import requests 
from bs4 import BeautifulSoup 


SEARCH_TERM = 'coca-cola' 

with requests.Session() as session: 
    session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'} 

    # get the current search state 
    response = session.get("http://tmsearch.uspto.gov/") 
    soup = BeautifulSoup(response.content, "html.parser") 
    link = soup.find("a", text="Basic Word Mark Search (New User)")["href"] 

    session.get(urljoin(response.url, link)) 

    state = parse_qs(link)['state'][0] 

    # perform a search 
    response = session.post("http://tmsearch.uspto.gov/bin/showfield", data={ 
     'f': 'toc', 
     'state': state, 
     'p_search': 'search', 
     'p_s_All': '', 
     'p_s_ALL': SEARCH_TERM + '[COMB]', 
     'a_default': 'search', 
     'a_search': 'Submit' 
    }) 

    # print search results 
    soup = BeautifulSoup(response.content, "html.parser") 

    print(soup.find("font", color="blue").get_text()) 

    table = soup.find("th", text="Serial Number").find_parent("table") 
    for row in table('tr')[1:]: 
     print(row('td')[1].get_text()) 

それはデモンストレーションの目的のために、最初の検索結果ページからすべてのシリアル番号の値を出力します。

関連する問題