【问题标题】:I want to scrape all members details from table with BeautifulSoup我想用 BeautifulSoup 从表中刮掉所有成员的详细信息
【发布时间】:2019-03-12 07:04:18
【问题描述】:
import requests
from bs4 import BeautifulSoup

url = 'http://www.gmcgujarat.org/searchdoctor.aspx'
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')

name = soup.find(" ")
for count in range(3333,4444):
        data = {name: " "}
        r = requests.post(url, data=data)
        soup = BeautifulSoup(r.text, 'html.parser')
    
        table = soup.find('table',{"id":"divtest"})
        for tr in table.find_all('tr',class_='odd')[1:5]:
            print tr.text

代码没有给出“tr”和“td”数据,因为“tr”以奇数和偶数形式给出,我不知道如何从中抓取数据。

【问题讨论】:

  • 如果你想废弃数据,为什么要使用'request.post'而不是你应该使用'request.get'
  • 我试过但它不起作用..@Mr.斯塔克

标签: python beautifulsoup


【解决方案1】:

获取本网站所有td 值的最简单方法是

data = {name: " "}
r = requests.post(url, data=data)
soup = BeautifulSoup(r.text, 'html.parser')

table = soup.find('table',{"id":"divtest"})
tr_arr = []
for tr in table.find_all('tr'):
  tr_arr.append([td.string for td in tr.find_all('td')])

因为您需要进一步挖掘tr 以找到所有tds。


但是假设你只关心class='odd',那么在find_all 中添加class_='odd' 已经是正确的方法了。

但是,如果某些行 (tr) 包含您不想要的数据怎么办。假设您只想获取带有class='odd'class='even' 的所有行,但有些行带有class='na'

实际上,您可以像这样将 dict 传递给find_all 中的类标识符:

table.find_all('tr', {"class": ["odd", "even"]})

或者更多地添加您的特定逻辑

table.find_all('tr', class_= lamdba x: x is not None and x in ['odd','even'])

【讨论】:

  • 我没有得到它,你能帮我写代码吗?@MatrixTai
  • @ghate,和你写的代码差不多,我只是把最后一部分改成查找td。我添加了您的代码的一部分以进行澄清。
  • @ghate,你确定你可以通过r = requests.post(url, data=data)获得目标html文本吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 2021-05-21
  • 2017-09-11
  • 2020-11-22
相关资源
最近更新 更多