【问题标题】:Beautifulsoup: How do I get the text from a webpage into dataframe?Beautifulsoup:如何将网页中的文本获取到数据框中?
【发布时间】:2021-05-17 04:02:39
【问题描述】:

我正在尝试使用 beautifulsoup 将日期值放入数据框中。

我想得到“2021 年 5 月 17 日”

我该怎么做?

我现有的代码:

import pandas as pd
from selenium import webdriver
from bs4 import BeautifulSoup as bs

browser = webdriver.Chrome()

urls = {
    "https://www.oddsportal.com/matches/soccer/"
}
class GameData:

    def __init__(self):
        self.date = []

def parse_data(url):
    browser.get(url)
    df = pd.read_html(browser.page_source, header=0)[0]
    html = browser.page_source
    soup = bs(html, "lxml")
    cont = soup.find('div', {'id': 'wrap'})
    content = cont.find('div', {'id': 'col-content'})
    content = content.find('table', {'class': 'table-main'}, {'id': 'table-matches'})
    main = content.find('th', {'class': 'first2 tl'})
    if main is None:
        return None
    count = main.findAll('a')
    country = count[0].text
    league = count[1].text

如何获取df 中的日期值?

【问题讨论】:

  • 那么你能找到日期还是只想用那个日期创建一个数据框??
  • 我有一个来自这个页面的数据框。我希望将日期附加到数据框中。另外,如果我可以将其转换为日期时间对象,那就太好了。

标签: python pandas web-scraping beautifulsoup


【解决方案1】:

我不确定你在这里对类的使用,是否所有函数都是它的一部分,df是否真的是你想要的形状和内容,你当然需要返回df。除此之外,为了回答你的确切问题,在第二个函数中,把它放在最后:

date = datetime.datetime.strptime(soup.select_one('#col-content h1').text.split(', ')[-1],'%d %b %Y') #.date()
df['date'] = date

记得import datetime。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2021-01-13
    相关资源
    最近更新 更多