如何使用python从网页中提取数据

2024-09-27 00:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能指出我做错了什么吗?你知道吗

Enter Item name:Rockfish Traceback (most recent call last): File "C:\Users\partn_000\Desktop\sarvesh\Python Source Code\working\jellyneoscraper.py", line 45, in search(br, ITEMNAME) File "C:\Users\partn_000\Desktop\sarvesh\Python Source Code\working\jellyneoscraper.py", line 33, in search increment = increment[0] IndexError: list index out of range

这是我写的代码

#Library Imports
import mechanize
import cookielib
import re
import sys
import time
import os.path
from operator import itemgetter
import ctypes
ctypes.windll.kernel32.SetConsoleTitleA("test")


def init_browser():
    br = mechanize.Browser()
    br.set_handle_equiv(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
    br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36')]
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    return br


def search(br, ITEMNAME):
    datapage = br.open('http://items.jellyneo.net/index.php?go=show_items&name=' +ITEMNAME +'&name_type=exact&desc=&cat=0&specialcat=0&status=0&rarity=0&sortby=name&numitems=20')
    f = open('search.html', 'w')
    f.write(datapage.read())
    f.close()
    value = re.findall('style="font-weight:bold;">(.+) NP</a></td>"',datapage.read())  #(.+) is replaced in place of required value
    value = value[0].replace(",","")
    value = int(value)
    print value
#http://items.jellyneo.net/index.php?go=show_items&name=Rockfish&name_type=exact&desc=&cat=0&specialcat=0&status=0&rarity=0&sortby=name&numitems=20


#('style="font-weight:bold;"> (.+) NP</a>"',search.read())


ITEMNAME = raw_input('Enter Item name:eg. Rockfish')

br = init_browser()
search(br, ITEMNAME)

Tags: nameinbrimporttruehttpsearchindex
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:56

在您的搜索方法中,您读取整个页面并将其保存到一个文件中, 然后您尝试重新读取它,执行您的正则表达式,但您已经在页面的末尾,所以它返回空字符串。 你应该加上数据页.seek(0)再这样读之前:

datapage = br.open('http://items.jellyneo.net/index.php?go=show_items&name=' +ITEMNAME +'&name_type=exact&desc=&cat=0&specialcat=0&status=0&rarity=0&sortby=name&numitems=20')
f = open('search.html', 'w')
f.write(datapage.read())
f.close()
datapage.seek(0)
value = re.findall('style="font-weight:bold;">(.+) NP</a></td>"',datapage.read())  #(.+) is replaced in place of required value
value = value[0].replace(",","")
value = int(value)

相关问题 更多 >

    热门问题