「退屈なことはPythonにやらせよう」11章のWebスクレイピングで、Googleの検索結果上位5件を自動で開くプログラムを書いているのですが、下記の2点で躓いています。
1.本書ではコマンドプロンプトに「'拡張子なしのファイル名' '検索したいワード'」でプログラムが実行されると書いてあるのですが、「[Errno 2] No such file or directory」のエラーが出てしまう。「'ファイル名.py' '検索したいワード'」にすると上手くいくのですが、違いが調べてもわかりません。PathにPython.exeのディレクトリを設定したりスクリプトがあるフォルダを設定しましたが駄目でした。
2.実行すると、「C:\Users\ユーザ名\Documents\Python Scripts\lucky.py:11: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
The code that caused this warning is on line 11 of the file C:\Users\s2160085.MAX-D4.000\Documents\Python Scripts\lucky.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor.」という表記が出て検索結果が表示されない。
→2.に関してはbs4.BeautifulSoupの第2引数に'html.parser'を入れて解決しましたが、コマンドプロンプトで実行すると「Loading...」が表示されるだけ、Anacondaのインタラクティブシェルで実行するとAttributeError: '_ModuleLock' object has no attribute 'name'が表示されてしまいます。
_Modulelockを調べたのですがさっぱり分からず…。申し訳ありませんが教えて下さい。よろしくお願い致します。
python
1#! python3 2# lucky.py 3 4import requests, sys, webbrowser, bs4 5 6print("Loading...") 7res = requests.get("https://google.com/search?q=" + " ".join(sys.argv[1:])) 8res.raise_for_status() 9 10#TODO 上位の検索結果のリンクを取得する 11soup = bs4.BeautifulSoup(res.text, "html.parser") 12link_elems = soup.select(".r a") 13 14#TODO 各結果をブラウザのタブで開く 15num_open = min(5, len(link_elems)) 16for i in range(num_open): 17 webbrowser.open("https://google.com" + link_elems[i].get("href"))
あなたの回答
tips
プレビュー