【问题标题】:How do I handle sub and sup while using scrapy in the scenario below?在以下场景中使用 scrapy 时如何处理 sub 和 sup?
【发布时间】:2017-05-17 12:57:13
【问题描述】:

我正在尝试从下面显示的 HTML 格式中提取问题

<li > 
    <h3 > Number Theory - Factors < /h3 >
    <p lang = "title" > How many factors of 2 < sup > 5 < /sup > * 3 < sup > 6 < /sup > * 5 < sup > 2 < /sup > are perfect squares?< /p >

    <ol class = "xyz" >
        <li > 18 < /li >
        <li > 24 < /li >
        <li > 36 < /li >
        <li > 8 < /li >
    < / ol >
    <ul class="exp">
        <li class="grey fleft">
            <span class="qlabs_tooltip_bottom qlabs_tooltip_style_33" style="cursor:pointer;">
                <span>
                    <strong>Correct Answer</strong>Choice (B).</br>24
                </span> Correct answer
            </span>
        </li>
        <li class="primary fleft">
            <a href="factors_3.shtml">Explanatory Answer</a>
        </li>
        <li class="grey1 fleft">Factors - Perfect Squares</li>
        <li class="orange flrt">Medium</li>
    </ul>       
</li>

我的问题可以从我使用 XPath 表达式中提取出来normalize-space(//p[@class="soln"])

XPath 表达式提取并给我这个文本 24 * 53 * 74 有多少个因数是奇数?

我如何通过 sub 和 sup 得到问题? 可能性 1: 我得到的问题是“24 * 53 * 74 有多少个因数奇数?不丢失 sub 或 sup"

可能性 2 我得到的问题是“2^4 * 5^3 * 7^4 有多少个因数是奇数?基本上我不想改变问题的含义?”

【问题讨论】:

  • 你能清楚地解释发生了什么以及你想要什么。您提供的描述似乎与您添加的 html 无关
  • 有什么方法可以在不改变意思的情况下直接得到问题?
  • 我更新了我的问题@Tuks

标签: python xpath web-scraping scrapy scrapy-spider


【解决方案1】:

这不是很漂亮,但我们可以将&lt;sup&gt; 预先替换为^ 并删除剩余的&lt;/sup&gt;

In [1]: response = response.replace(body=response.body.replace("<sup>", "^").replace("</sup>", ""))

In [2]: response.xpath('normalize-space(//p[@lang="title"])').extract_first()
Out[2]: u'How many factors of 2 ^ 5 * 3 ^ 6 * 5 ^ 2 are perfect squares?'

【讨论】:

    【解决方案2】:

    我不熟悉 screpy,但我可以添加一些用 java 编写的代码示例来帮助你

    // get inner html of your question with `sup` or `sub` tags
    
    String question = driver.findElement(By.xpath("//p[@lang = 'title'] ")).getAttribute("innerHTML");
    
    // Replace the tags with symbols
    
    String newQuestion = question.replace("<sup>", "^").replace("</sup>", "");
    System.out.println(newQuestion);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-07
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      相关资源
      最近更新 更多