Reputation: 527
I need to extract data from HTML table from this website: https://1x2.lucksport.com/result_en.shtml?dt=2019-04-12&cid=156
I use Python, selenium and lxml with xpath
I want to extract each match odds The problem is that each match is in 2 row two : tr class="dtd2", then come two: tr class="dtd1"
I need the xpath that allow to extract the first row and his following row
driver.get(u)
t = html.fromstring(driver.page_source)
for i in t.xpath('//*[@id="odds_tb"]/table/tbody/tr[@class="dtd2"]/td[1]/text()'):
Upvotes: 1
Views: 1038
Reputation: 84465
A more verbose method
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as bs
import pandas as pd
import copy
d = webdriver.Chrome()
d.get('https://1x2.lucksport.com/result_en.shtml?dt=2019-04-12&cid=156')
WebDriverWait(d, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#odds_tb tr[class]")))
soup = bs(d.page_source, 'lxml')
rows = soup.select('#odds_tb tr[class]')
results = []
i = 1
headers = ['Competition', 'Date', 'Match' ,'OddsType', 'Home Win', 'Draw', 'Away Win', 'Result']
for row in rows[1:]:
cols = [td.text for td in row.select('td')]
if (i % 2 == 1):
record = {'Competition' : cols[0],
'Date' : cols[1],
'Match' : ' v '.join([cols[2], cols[6]]),
'OddsType' : 'average early odds',
'Home Win' : cols[3],
'Draw' : cols[4],
'Away Win' : cols[5],
'Result' : cols[7]}
else:
record['OddsType'] = 'average live odds'
record['Home Win'] = cols[0]
record['Draw'] = cols[1]
record['Away Win'] = cols[2]
results.append(copy.deepcopy(record))
i+=1
df = pd.DataFrame(results, columns = headers)
df.to_csv(r'C:\Users\User\Desktop\data.csv', sep=',', encoding='utf-8-sig',index = False )
d.quit()
Upvotes: 1
Reputation: 54984
It looks like you want to iterate the odd trs and then include the "next" tr. In css that looks like:
.dtd1:nth-child(odd),.dtd2:nth-child(odd)
You can get odds with xpath too, just add:
[position() mod 2 = 1]
Upvotes: 0
Reputation: 33384
You can use both selenium
and pandas
to get the table info.
from selenium import webdriver
import time
import pandas as pd
driver = webdriver.Chrome()
driver.get("https://1x2.lucksport.com/result_en.shtml?dt=2019-04-12&cid=156")
time.sleep(3)
htmlcontent=driver.page_source
tables=pd.read_html(htmlcontent)
print(tables[14])
Upvotes: 0