网页抓取返回空括号

时间:2020-01-16 14:52:12

标签: python-3.x web-scraping

Python的新手,但仍然可以在线自学等。

我正在尝试使用beautifulsoup构建一个网络抓取工具,到目前为止,我已经找到了要抓取并打印的页面上的哪些元素,但是在测试了第一个元素后,它只打印了空括号而不是html / text在我需要的网站上。

这是到目前为止的代码:

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.expireddomains.co.nz/search.php?action=search&status=6&results_per_page=100&page=2')
soup = BeautifulSoup (source.text, 'html.parser')
elems = soup.select('body > table > tbody > tr > td:nth-child(3) > div.PageTabsBox > form:nth-child(4) > table.DomainList > tbody > tr:nth-child(2) > td:nth-child(2) > a')
print(elems)

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

尝试一下。

from simplified_scrapy.request import req
from simplified_scrapy.simplified_doc import SimplifiedDoc
url = 'https://www.expireddomains.co.nz/search.php?action=search&status=6&results_per_page=100&page=2'
html = req.get(url)
doc = SimplifiedDoc(html)
table = doc.getElement('TABLE',attr='class',value='DomainList')
trs = table.TRs
for tr in trs:
  # print ([td.text for td in tr.children])
  pass
elems = trs[1].children[1].a
print(elems)
print(doc.absoluteUrl(url,elems.href))

结果:

{'href': '/register.php?domain_id=2201986', 'tag': 'a', 'html': 'academyoflearning.co.nz'}
https://www.expireddomains.co.nz/register.php?domain_id=2201986

您可以获取SimplifiedDoc here

的示例

答案 1 :(得分:0)

这会刮掉所有子节点的链接。

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.expireddomains.co.nz/search.php?action=search&status=6&results_per_page=100&page=2')
soup = BeautifulSoup (source.text, 'html.parser')

Link = []
div = soup.find('div', {'class': 'PageTabsBox'})
TR = div.findAll('tr')
for tr in TR:
    TD = tr.findAll('td')

    for td in TD:
        try:
            link = td.find('a')
            link = link['href']
            Link.append(link)
        except:
            continue
print(Link)
print(Link[6])

答案 2 :(得分:0)

这假定您使用的是BeautifulSoup 4.7+,其中包含改进的选择库。

我想回答为什么,您所做的没有用,然后向您展示如何轻松地使它起作用。

您的代码不起作用的原因有两个。当您在浏览器中检查HTML时,它有时可以向您显示解析器自由修改的HTML,以符合其认为的意图,并为您提供更合适的HTML。例如,当您请求原始HTML时,没有tbody标签,但是在浏览器中,它会自动插入它,因为它更合适。

如果在原始HTML中找不到

html.parser,则不会插入tbody。如果您希望在BeautifulSoup中完成此操作,则需要安装html5lib并使用该解析器soup = BeautifulSoup (source.text, 'html5lib')

有时,当我遇到一个意外的解析器问题时,我会将汤对象的内容打印到一个单独的文件中,以便我可以分析与在浏览器中查看它时所期望的不同之处。


因此,假设我们仍在使用html.parser,让我们简化选择,也不要寻找tbody

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.expireddomains.co.nz/search.php?action=search&status=6&results_per_page=100&page=2')
soup = BeautifulSoup (source.text, 'html.parser')
elems = soup.select('table.DomainList > tr:nth-child(2) > td:nth-child(2) > a')
print(elems)

输出

[<a href="/register.php?domain_id=2196993">absca.co.nz</a>] 
相关问题