简体   繁体   English

使用BeautifulSoup或LXML.HTML进行Web爬网

[英]WebScraping with BeautifulSoup or LXML.HTML

I have seen some webcasts and need help in trying to do this: I have been using lxml.html. 我已经看过一些网络广播,并且在尝试执行此操作时需要帮助:我一直在使用lxml.html。 Yahoo recently changed the web structure. 雅虎最近改变了网络结构。

target page; 目标页面;

http://finance.yahoo.com/quote/IBM/options?date=1469750400&straddle=true http://finance.yahoo.com/quote/IBM/options?date=1469750400&straddle=true

In Chrome using inspector: I see the data in 在Chrome中使用检查器:我在

 //*[@id="main-0-Quote-Proxy"]/section/section/div[2]/section/section/table

then some more code 然后再写一些代码

How Do get this data out into a list. 如何将这些数据放入列表中。 I want to change to other stock from "LLY" to "Msft"? 我想将其他股票从“ LLY”更改为“ Msft”吗?
How do I switch between dates....And get all months. 我该如何在日期之间切换...。

I know you said you can't use lxml.html . 我知道您说您不能使用lxml.html But here is how to do it using that library, because it is very good library. 但是这里是使用该库的方法,因为它是非常好的库。 So I provide the code using it, for completeness, since I don't use BeautifulSoup anymore -- it's unmaintained, slow and has ugly API. 因此,出于完整性考虑,我提供了使用它的代码,因为我不再使用BeautifulSoup了-它没有维护,运行缓慢并且具有丑陋的API。

The code below parses the page and writes the results in a csv file. 下面的代码解析该页面并将结果写入csv文件中。

import lxml.html
import csv

doc = lxml.html.parse('http://finance.yahoo.com/q/os?s=lly&m=2011-04-15')
# find the first table contaning any tr with a td with class yfnc_tabledata1
table = doc.xpath("//table[tr/td[@class='yfnc_tabledata1']]")[0]

with open('results.csv', 'wb') as f:
    cf = csv.writer(f)
    # find all trs inside that table:
    for tr in table.xpath('./tr'):
        # add the text of all tds inside each tr to a list
        row = [td.text_content().strip() for td in tr.xpath('./td')]
        # write the list to the csv file:
        cf.writerow(row)

That's it! 而已! lxml.html is so simple and nice!! lxml.html是如此简单和不错! Too bad you can't use it. 太糟糕了,您不能使用它。

Here's some lines from the results.csv file that was generated: 以下是所生成的results.csv文件中的一些行:

LLY110416C00017500,N/A,0.00,17.05,18.45,0,0,17.50,LLY110416P00017500,0.01,0.00,N/A,0.03,0,182
LLY110416C00020000,15.70,0.00,14.55,15.85,0,0,20.00,LLY110416P00020000,0.06,0.00,N/A,0.03,0,439
LLY110416C00022500,N/A,0.00,12.15,12.80,0,0,22.50,LLY110416P00022500,0.01,0.00,N/A,0.03,2,50

If you'd like raw json try MSN 如果您想使用原始json,请尝试使用MSN

http://www.msn.com/en-us/finance/stocks/optionsajax/126.1.UNH.NYS/

You can also specify an expiration date ?date=11/14/2014 您还可以指定到期日期?date=11/14/2014

http://www.msn.com/en-us/finance/stocks/optionsajax/126.1.UNH.NYS/?date=11/14/2014

If you prefer Yahoo json 如果您更喜欢Yahoo json

http://finance.yahoo.com/q/op?s=LLY

But you have to extract it from the html 但是您必须从html中提取它

import re

m = re.search('<script>.+({"applet_type":"td-applet-options-table".+);</script>', resp.content)

data = json.loads(m.group(1))
as_dicts = data['models']['applet_model']['data']['optionData']['_options'][0]['straddles']

Expirations are here 到期在这里

data['models']['applet_model']['data']['optionData']['expirationDates']

Convert iso to unix timestamp as here 转换成ISO到UNIX时间戳这里

Then re-request the other expirations with the unix timestamp 然后使用unix时间戳重新请求其他到期时间

http://finance.yahoo.com/q/op?s=LLY&date=1414713600

Here is a simple example to extract all data from the stock tables: 这是一个从库存表中提取所有数据的简单示例:

import urllib
import lxml.html
html = urllib.urlopen('http://finance.yahoo.com/q/op?s=lly&m=2014-11-15').read()
doc = lxml.html.fromstring(html)
# scrape figures from each stock table
for table in doc.xpath('//table[@class="details-table quote-table Fz-m"]'):
    rows = []
    for tr in table.xpath('./tbody/tr'):
        row = [td.text_content().strip() for td in tr.xpath('./td')]
        rows.append(row)
    print rows

Then to extract for different stocks and dates you need to change the URL. 然后要提取不同的股票和日期,您需要更改URL。 Here is Msft for the previous day: http://finance.yahoo.com/q/op?s=msft&m=2014-11-14 这是前一天的Msft: http : //finance.yahoo.com/q/op? s=msft&m=2014-11-14

Basing the Answer on @hoju: 将答案基于@hoju:

import lxml.html
import calendar
from datetime import datetime

exDate  = "2014-11-22"
symbol  = "LLY"
dt      = datetime.strptime(exDate, '%Y-%m-%d')
ym      = calendar.timegm(dt.utctimetuple())

url     = 'http://finance.yahoo.com/q/op?s=%s&date=%s' % (symbol, ym,)
doc     = lxml.html.parse(url)
table   = doc.xpath('//table[@class="details-table quote-table Fz-m"]/tbody/tr')

rows    = []        
for tr in table:
     d = [td.text_content().strip().replace(',','') for td in tr.xpath('./td')]
     rows.append(d)

print rows 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM