我尝试从https://www.lotto.de/de/ergebnisse/lotto-6aus49/archiv.html中提取乐透号码(我知道有一种更简单的方法,但它是用于学习)。



与Python一起尝试了beautifulsoup以下内容:

from BeautifulSoup import BeautifulSoup
import urllib2

url="https://www.lotto.de/de/ergebnisse/lotto-6aus49/archiv.html"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
numbers=soup.findAll('li',{'class':'winning_numbers.boxRow.clearfix'})

for number in numbers:
    print number['li']+","+number.string


什么也不返回,这实际上是我期望的。我阅读了该教程,但仍然不完全理解该解析。有人可以给我提示吗?

谢谢!

最佳答案

由于数据内容是动态生成的,因此您可以使用Selenium或类似方式将一种EASIER解决方案用作浏览器来模拟操作(我将PhantomJS用作webdriver),如下所示:

from selenium import webdriver

url="https://www.lotto.de/de/ergebnisse/lotto-6aus49/archiv.html"
# I'm using PhantomJS, you may use your own...
driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
driver.get(url)
soup = BeautifulSoup(driver.page_source)
# I just simply go through the div class and grab all number texts
# without special number, like in the Sample
for ul in soup.findAll('div', {'class': 'winning_numbers'}):
    n = ','.join(li for li in ul.text.split() if li.isdigit())
    if n:
        print 'number: {}'.format(n)

number: 6,25,26,27,28,47


要同时获取特殊号码:

for ul in soup.findAll('div', {'class': 'winning_numbers'}):
    # grab only numeric chars, you may apply your own logic here
    n = ','.join(''.join(_ for _ in li if _.isdigit()) for li in ul.text.split())
    if n:
        print 'number: {}'.format(n)

number: 6,25,26,27,28,47,5 # with special number


希望这可以帮助。

08-19 06:37