【问题标题】:Data fetching from table on website从网站上的表中获取数据
【发布时间】:2018-10-26 01:26:32
【问题描述】:

我在从网页上的表格中提取或报废数据方面需要帮助。我用的是漂亮的汤。无法提取具有表号的表。 6. 任何帮助将不胜感激:

需要表 6 中的所有行数据。一个网页中有多个表格,但我只需要合规信息的数据,不知道该怎么做。

网址是here

我的代码如下:

link = ["http://ec.europa.eu/environment/ets/ohaDetails.do?returnURL=&languageCode=en&accountID=&registryCode=&buttonAction=all&action=&account.registryCode=&accountType=&identifierInReg=&accountHolder=&primaryAuthRep=&installationIdentifier=&installationName=&accountStatus=&permitIdentifier=&complianceStatus=&mainActivityType=-1&searchType=oha&resultList.currentPageNumber=1&nextList=Next%C2%A0%3E&selectedPeriods="]

for pagenum, links in enumerate(link[start:end]):

  print(links)
  r = requests.get(links)

  time.sleep(random.randint(2,5)) 

  soup = BeautifulSoup(r.content,"lxml")

  tree = html.fromstring(str(soup))

  value = []

  data_block = soup.find_all("table", {"class": "bordertb"})

  print (data_block)

  output = []

  for item in data_block:

    table_data = item.find_all("td", {"class": "tabletitle"})[0].table

    value.append([table_data])

    print (value)


  with open("Exhibit_2_EXP_data.tsv", "wb") as outfile:

    outfile = unicodecsv.writer(outfile, delimiter="\t")

   outfile.writerow(["Data_Output"])

   for item in value:

     outfile.writerow(item)

【问题讨论】:

    标签: python xpath web-scraping beautifulsoup request


    【解决方案1】:

    试试这个。下面的脚本应该从该表中获取您的内容。具体来说,您应该从上一个表开始操作(因为它有一个唯一的 ID),然后使用适当的方法,您可以获得所需表的内容。以下是我为实现相同目标所做的工作:

    import requests
    from bs4 import BeautifulSoup
    
    url = "http://ec.europa.eu/environment/ets/ohaDetails.do?returnURL=&languageCode=en&accountID=&registryCode=&buttonAction=all&action=&account.registryCode=&accountType=&identifierInReg=&accountHolder=&primaryAuthRep=&installationIdentifier=&installationName=&accountStatus=&permitIdentifier=&complianceStatus=&mainActivityType=-1&searchType=oha&resultList.currentPageNumber=1&nextList=Next%C2%A0%3E&selectedPeriods="
    
    r = requests.get(url)
    soup = BeautifulSoup(r.text,"lxml")
    for items in soup.find(id="tblInstallationContacts").find_next_sibling().find_all("tr")[:-5]:
        data = [item.get_text(strip=True) for item in items.find_all("td")]
        print(data)
    

    【讨论】:

    • 感谢 SIM 卡,它工作正常,数据以所需格式输入。感谢您的帮助:)
    • 不要忘记勾选我的答案旁边的向上/向下按钮之间的灰色复选标记,以将其选为接受的解决方案。看这里What should I do when someone answers my question?。谢谢
    • 能否请您帮忙根据 Span HTML 标记分隔表格的输出值,以便 URL ec.europa.eu/environment/ets/… 的输出类似于 195640 421 *****
    • 有人可以帮忙吗?
    • 解决了这个问题。使用 str.split 和 str.join
    猜你喜欢
    • 2013-10-18
    • 2013-05-21
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多