用python编程打开页面

问题描述 投票:3回答:3

您可以从此webpage中提取VIN号码吗?

我尝试过urllib2.build_opener,请求并机械化。我也提供了用户代理,但是他们都看不到VIN。

opener = urllib2.build_opener()
opener.addheaders = [('User-agent',('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) ' 'AppleWebKit/535.1 (KHTML, like Gecko) ' 'Chrome/13.0.782.13 Safari/535.1'))]
page = opener.open(link)
soup = BeautifulSoup(page)

table = soup.find('dd', attrs = {'class': 'tip_vehicleStats'})
vin = table.contents[0]
print vin
python web-scraping beautifulsoup urllib2 mechanize
3个回答
5
投票

您可以为此目的使用浏览器自动化工具。

例如,这个简单的硒脚本可以完成您的工作。

from selenium import webdriver
from bs4 import BeautifulSoup

link = "https://www.iaai.com/Vehicles/VehicleDetails.aspx?auctionID=14712591&itemID=15775059&RowNumber=0"
browser = webdriver.Firefox()
browser.get(link)
page = browser.page_source

soup = BeautifulSoup(page)

table = soup.find('dd', attrs = {'class': 'tip_vehicleStats'})
vin = table.contents.span.contents[0]
print vin

BTW,table.contents[0]打印整个范围,包括范围标签。

[table.contents.span.contents[0]仅打印VIN号


7
投票

该页面上有许多信息是通过Javascript加载和显示的(可能是通过Ajax调用),很可能是直接防止刮擦的信息。因此,要抓取此内容,您要么需要使用运行Javascript的浏览器,然后对其进行远程控制,要么使用javascript编写抓取工具本身,或者您需要对网站进行解构,并确切地了解它使用Javascript加载的内容以及操作方式,然后查看是否您可以重复这些呼叫。


2
投票

您可以使用硒,它会调用浏览器。这对我有用:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

# See: http://stackoverflow.com/questions/20242794/open-a-page-programatically-in-python
browser = webdriver.Firefox() # Get local session of firefox
browser.get("https://www.iaai.com/Vehicles/VehicleDetails.aspx?auctionID=14712591&itemID=15775059&RowNumber=0") # Load page


time.sleep(0.5) # Let the page load


# Search for a tag "span" with an attribute "id" which contains "ctl00_ContentPlaceHolder1_VINc_VINLabel"
e=browser.find_element_by_xpath("//span[contains(@id,'ctl00_ContentPlaceHolder1_VINc_VINLabel')]")
e.text
# Works for me : u'4JGBF7BE9BA648275'

browser.close()
© www.soinside.com 2019 - 2024. All rights reserved.