この Web サイトをクロールする必要があります。ボタンをクリックすると JavaScript が実行され、回答ウィンドウが表示される頭の体操 Web サイトです。
<tr>
<td width="60" bgcolor="#ECF5FF"> <p align="center"><font color="#800000".htm>1</font></p></td>
<td width="539" bgcolor="#ECF5FF"> <font color="#008080">一种东西,东方人的短,西方人的长,结婚后女的就可以用男的这东西,和尚有但是不用它&nbsp;</font>
</td>
<td width="95" bgcolor="#ECF5FF"> <p align="center">
<INPUT onClick="MM_popupMsg('答案:名字&nbsp;')" type=button value=答案 name=button8639 style='font-size:12px;height:18px;border:1px solid black;'>
</p></td>
</tr>
これは、質問と回答をクロールするために私が書いたコードです。質問を取得することはできますが、回答を取得できませんでした。(答えを印刷すると、それは空[]
です。)
questions = hxs.select('//td[@width="539"]/font/text()').extract()
answers = hxs.select('//td[@width="95"]/INPUT/@onClick').extract()
答えは、onclick スクリプトの内容です。つまり、次の文字列を取得したいのです。
MM_popupMsg('答案:名字&nbsp;')
これは私のスパイダーです:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
import re
class ReviewSpider(BaseSpider):
name = "2345jzw"
allowed_domains = ['2345.com/jzw']
start_urls = ['http://www.2345.com/jzw/index.htm']
page = 1
while page <= 1:
url = 'http://www.2345.com/jzw/%d.htm' % page
start_urls.append(url)
page = page + 1
def parse(self, response):
hxs = HtmlXPathSelector(response)
questions = hxs.select('//td[@width="539"]/font/text()').extract()
answers = hxs.select('//td[3]/p/INPUT/@onClick').extract()
print questions
print answers
id = 1
while id <= 50:
question = questions[id - 1]
question = re.sub(r'<[^>]*?>', '', str(question.encode('utf8')))
question = ' '.join(question.split())
question = question.replace('&', ' ')
question = question.replace('\'', ' ')
question = question.replace(',', ';')
answer = answers[id - 1]
answer = re.sub(r'<[^>]*?>', '', str(answer.encode('utf8')))
answer = ' '.join(answer.split())
answer = answer.replace('&', ' ')
answer = answer.replace('\'', ' ')
answer = answer.replace(',', ';')
file = open('crawled.xml', 'a')
file.write(question)
file.write(",")
file.write(answer)
file.write("\n")
file.close()
id = id + 1
私が試してみました
hxs.select('//INPUT/@onClick').extract()
しかし、それはまだ機能していません。パスの何が問題になっていますか?
質問が正常に抽出されたことに注意してください。質問と回答の構造は非常に似ています。なぜ答えが空なのですか?